repo stringclasses 11
values | bug_origin_pr int64 102 23.8k | bug_description stringlengths 431 1.34k | correct_fix stringlengths 293 9.82k | category stringclasses 6
values | severity stringclasses 3
values | impact stringclasses 5
values |
|---|---|---|---|---|---|---|
astropy/astropy | 6,746 | Nested `CompoundModel` separability was computed using an identity block instead of the child model’s actual dependency matrix. In `_cstack`, when `right` is already a matrix, the code did:
```python
cright = np.zeros((noutp, right.shape[1]))
cright[-right.shape[0]:, -right.shape[1]:] = 1
```
This overwrites `right`’... | diff --git a/astropy/modeling/separable.py b/astropy/modeling/separable.py
--- a/astropy/modeling/separable.py
+++ b/astropy/modeling/separable.py
@@ -242,7 +242,7 @@ def _cstack(left, right):
cright = _coord_matrix(right, 'right', noutp)
else:
cright = np.zeros((noutp, right.shape[1]))
- ... | Structural Bugs | Medium | Functional Suitability |
astropy/astropy | 8,540 | The error message incorrectly formats required columns when validation fails. When `_required_columns` contains multiple columns (e.g., `["time", "flux"]`), the message only displays the first element using `required_columns[0]`, making it appear that only `'time'` is required:
```python
raise ValueError("{} object is... | diff --git a/astropy/timeseries/core.py b/astropy/timeseries/core.py
--- a/astropy/timeseries/core.py
+++ b/astropy/timeseries/core.py
@@ -55,6 +55,13 @@ class BaseTimeSeries(QTable):
_required_columns_relax = False
def _check_required_columns(self):
+ def as_scalar_or_list_str(obj):
+ if ... | Structural Bugs | Low | Usability |
astropy/astropy | 10,229 | The `world_to_pixel_values` method in `SlicedLowLevelWCS` incorrectly fills sliced-out world coordinates with the constant value `1.0` instead of the actual world coordinate values corresponding to the slice position.
```python
# Buggy code:
for iworld in range(self._wcs.world_n_dim):
if iworld in self._world_keep... | diff --git a/astropy/wcs/wcsapi/wrappers/sliced_wcs.py b/astropy/wcs/wcsapi/wrappers/sliced_wcs.py
--- a/astropy/wcs/wcsapi/wrappers/sliced_wcs.py
+++ b/astropy/wcs/wcsapi/wrappers/sliced_wcs.py
@@ -243,6 +243,8 @@ def pixel_to_world_values(self, *pixel_arrays):
return world_arrays
def world_to_pixel_va... | Structural Bugs | High | Functional Suitability |
astropy/astropy | 1,117 | The `is_fits` identifier function unconditionally accesses `args[0]` when neither `fileobj` nor a FITS-extension filepath is provided, causing an IndexError when `args` is empty.
```python
def is_fits(origin, filepath, fileobj, *args, **kwargs):
# ... fileobj check ...
elif filepath is not None:
if fil... | diff --git a/astropy/io/fits/connect.py b/astropy/io/fits/connect.py
--- a/astropy/io/fits/connect.py
+++ b/astropy/io/fits/connect.py
@@ -65,10 +65,9 @@ def is_fits(origin, filepath, fileobj, *args, **kwargs):
fileobj.seek(pos)
return sig == FITS_SIGNATURE
elif filepath is not None:
- if ... | Structural Bugs | Medium | Reliability |
astropy/astropy | 102 | The `_format_float()` function unnecessarily expands float representations, causing valid FITS cards to fail. When formatting `0.009125`, the function uses `f"{value:.16G}"` which produces `0.009124999999999999` (17 characters), consuming extra space and forcing comment truncation.
```python
# Current behavior:
value ... | diff --git a/astropy/io/fits/card.py b/astropy/io/fits/card.py
--- a/astropy/io/fits/card.py
+++ b/astropy/io/fits/card.py
@@ -1298,31 +1298,17 @@ def _format_value(value):
def _format_float(value):
- """Format a floating number to make sure it gets the decimal point."""
- value_str = f"{value:.16G}"
- if... | Structural Bugs | Medium | Functional Suitability |
astropy/astropy | 11,108 | The regex pattern for parsing FITS card string values fails to properly handle escaped single quotes (`''`) when the value spans multiple continuation cards. The pattern `_strg_comment_RE` lacks an end-of-string anchor, causing it to incorrectly match partial strings during continuation card parsing.
```python
# Origi... | diff --git a/astropy/io/fits/card.py b/astropy/io/fits/card.py
--- a/astropy/io/fits/card.py
+++ b/astropy/io/fits/card.py
@@ -66,7 +66,7 @@ class Card(_Verify):
# followed by an optional comment
_strg = r"\'(?P<strg>([ -~]+?|\'\'|) *?)\'(?=$|/| )"
_comm_field = r"(?P<comm_field>(?P<sepr>/ *)(?P<comm>(.|... | Structural Bugs | Medium | Functional Suitability |
astropy/astropy | 14,175 | The `_arithmetic_mask` method has a logic error in its conditional checks. When both operands have masks, it incorrectly checks `operand is None` instead of `operand.mask is None`:
```python
elif operand is None: # Wrong - checks if operand object is None
return deepcopy(self.mask)
else:
return handle_mask(se... | diff --git a/astropy/nddata/mixins/ndarithmetic.py b/astropy/nddata/mixins/ndarithmetic.py
--- a/astropy/nddata/mixins/ndarithmetic.py
+++ b/astropy/nddata/mixins/ndarithmetic.py
@@ -520,10 +520,10 @@ def _arithmetic_mask(self, operation, operand, handle_mask, axis=None, **kwds):
elif self.mask is None and ope... | Structural Bugs | Medium | Reliability |
astropy/astropy | 3,072 | The `quantity_input` decorator attempts to convert return values to the annotated unit type without checking if the annotation is `None`. When a constructor is properly type-hinted with `-> None`, the decorator tries to call `.to()` on the `None` return value, causing an `AttributeError`.
```python
@u.quantity_input
d... | diff --git a/astropy/units/decorators.py b/astropy/units/decorators.py
--- a/astropy/units/decorators.py
+++ b/astropy/units/decorators.py
@@ -220,7 +220,7 @@ def wrapper(*func_args, **func_kwargs):
# Call the original function with any equivalencies in force.
with add_enabled_equivalencies(se... | Structural Bugs | Medium | Reliability |
django/django | 6,612 | The `content_type.save()` call ignores the database routing context established by the surrounding `transaction.atomic(using=db)` block. While the transaction is correctly scoped to the target database, the save operation itself doesn't specify which database to use, causing Django's ORM to fall back to the default dat... | diff --git a/django/contrib/contenttypes/management/__init__.py b/django/contrib/contenttypes/management/__init__.py
--- a/django/contrib/contenttypes/management/__init__.py
+++ b/django/contrib/contenttypes/management/__init__.py
@@ -24,7 +24,7 @@ def _rename(self, apps, schema_editor, old_model, new_model):
... | Interface, Integration, and System Bugs | High | Reliability |
django/django | 10,448 | The fast-delete optimization path fails to clear the primary key on deleted model instances. When a model has no dependencies, Django uses `can_fast_delete()` to bypass the full deletion collector and directly execute a DELETE query. However, this code path returns immediately after the database deletion without nullif... | diff --git a/django/db/models/deletion.py b/django/db/models/deletion.py
--- a/django/db/models/deletion.py
+++ b/django/db/models/deletion.py
@@ -277,6 +277,7 @@ def delete(self):
if self.can_fast_delete(instance):
with transaction.mark_for_rollback_on_error():
count ... | Structural Bugs | Medium | Reliability |
django/django | 7,482 | The `match()` method incorrectly includes `None` values in the kwargs dictionary when optional named groups in the regex pattern don't match. When a named group is optional (e.g., `(?P<optional_param>...)?`), `match.groupdict()` returns the key with a `None` value if that group doesn't match.
```python
# Before fix:
k... | diff --git a/django/urls/resolvers.py b/django/urls/resolvers.py
--- a/django/urls/resolvers.py
+++ b/django/urls/resolvers.py
@@ -153,7 +153,7 @@ def match(self, path):
# If there are any named groups, use those as kwargs, ignoring
# non-named groups. Otherwise, pass all non-named arguments a... | Structural Bugs | Medium | Functional Suitability |
django/django | 9,340 | The `get_combinator_sql` method modifies combined query objects in-place when synchronizing column selections, causing subsequent `values()`/`values_list()` calls to return stale results.
```python
# In get_combinator_sql:
if not compiler.query.values_select and self.query.values_select:
compiler.query.set_values(... | diff --git a/django/db/models/sql/compiler.py b/django/db/models/sql/compiler.py
--- a/django/db/models/sql/compiler.py
+++ b/django/db/models/sql/compiler.py
@@ -426,6 +426,7 @@ def get_combinator_sql(self, combinator, all):
# must have the same columns list. Set the selects defined on
... | Structural Bugs | Medium | Functional Suitability |
django/django | 10,764 | The `Avg` and `Sum` aggregate classes lack the `allow_distinct` attribute, causing them to reject DISTINCT queries that are valid SQL operations. Prior to Django 2.2, these aggregates silently ignored the DISTINCT parameter, but the framework now raises an exception when DISTINCT is used with aggregates that don't expl... | diff --git a/django/db/models/aggregates.py b/django/db/models/aggregates.py
--- a/django/db/models/aggregates.py
+++ b/django/db/models/aggregates.py
@@ -99,6 +99,7 @@ def _get_repr_options(self):
class Avg(FixDurationInputMixin, NumericOutputFieldMixin, Aggregate):
function = 'AVG'
name = 'Avg'
+ allow_... | Requirements, Features, and Functionality Bugs | Medium | Functional Suitability |
django/django | 9,383 | The migration autodetector fails to generate dependencies when altering a field to a ForeignKey. When changing a UUIDField to a ForeignKey pointing to another app's model, the generated migration lacks the necessary dependency on the target model's app, causing a `ValueError: Related model cannot be resolved` at migrat... | diff --git a/django/db/migrations/autodetector.py b/django/db/migrations/autodetector.py
--- a/django/db/migrations/autodetector.py
+++ b/django/db/migrations/autodetector.py
@@ -912,6 +912,7 @@ def generate_altered_fields(self):
old_field_name = self.renamed_fields.get((app_label, model_name, field_name),... | Structural Bugs | High | Reliability |
django/django | 10,287 | The `_check_ordering` validation incorrectly rejects `pk` lookups on related fields because it attempts to resolve `pk` as a literal field name rather than recognizing it as an alias for the primary key.
```python
# In Meta.ordering validation:
for part in field.split(LOOKUP_SEP):
fld = _cls._meta.get_field(part) ... | diff --git a/django/db/models/base.py b/django/db/models/base.py
--- a/django/db/models/base.py
+++ b/django/db/models/base.py
@@ -1708,9 +1708,15 @@ def _check_ordering(cls):
fld = None
for part in field.split(LOOKUP_SEP):
try:
- fld = _cls._meta.get_field(... | Structural Bugs | Medium | Functional Suitability |
django/django | 9,192 | The `bulk_create` method ignores database-specific batch size limits when a user-provided `batch_size` is specified. The original code uses:
```python
batch_size = (batch_size or max(ops.bulk_batch_size(fields, objs), 1))
```
This logic only calculates the compatible batch size (`ops.bulk_batch_size()`) when `batch_s... | diff --git a/django/db/models/query.py b/django/db/models/query.py
--- a/django/db/models/query.py
+++ b/django/db/models/query.py
@@ -1209,7 +1209,8 @@ def _batched_insert(self, objs, fields, batch_size, ignore_conflicts=False):
if ignore_conflicts and not connections[self.db].features.supports_ignore_conflic... | Structural Bugs | Medium | Reliability |
django/django | 11,540 | Choices enum members lacked a `__str__()` override, so when a model field was assigned a `TextChoices/IntegerChoices` member, string coercion returned the enum’s repr-like name instead of the underlying value. Problematic pattern:
```py
obj = MyObject.objects.create(my_str_value=MyChoice.FIRST_CHOICE)
str(obj.my_str_v... | diff --git a/django/db/models/enums.py b/django/db/models/enums.py
--- a/django/db/models/enums.py
+++ b/django/db/models/enums.py
@@ -60,7 +60,13 @@ def values(cls):
class Choices(enum.Enum, metaclass=ChoicesMeta):
"""Class for creating enumerated choices."""
- pass
+
+ def __str__(self):
+ """
+ ... | Structural Bugs | Medium | Functional Suitability |
django/django | 6,491 | Django 2.2 unconditionally overwrites user-defined `get_<field>_display()` methods when a field has `choices`. In `Field.contribute_to_class()`, it always does:
```py
setattr(cls, 'get_%s_display' % self.name,
partialmethod(cls._get_FIELD_display, field=self))
```
This clobbers any model override like:
```py... | diff --git a/django/db/models/fields/__init__.py b/django/db/models/fields/__init__.py
--- a/django/db/models/fields/__init__.py
+++ b/django/db/models/fields/__init__.py
@@ -763,8 +763,12 @@ def contribute_to_class(self, cls, name, private_only=False):
if not getattr(cls, self.attname, None):
... | Interface, Integration, and System Bugs | High | Compatibility |
django/django | 4,657 | `parse_bits()` incorrectly flags valid keyword-only arguments as unexpected because it checks against `unhandled_kwargs` instead of the function’s keyword-only parameter list. Problematic code:
```py
if param not in params and param not in unhandled_kwargs and varkw is None:
raise TemplateSyntaxError(...)
```
For... | diff --git a/django/template/library.py b/django/template/library.py
--- a/django/template/library.py
+++ b/django/template/library.py
@@ -261,7 +261,7 @@ def parse_bits(parser, bits, params, varargs, varkw, defaults,
if kwarg:
# The kwarg was successfully extracted
param, value = kwa... | Structural Bugs | Medium | Functional Suitability |
django/django | 8,432 | Deleting an `index_together` could crash when the same columns are also in `unique_together` because the schema editor searched for any constraint matching the columns and `index=True`, which also matches unique constraints. In `alter_index_together()` it called:
```py
self._delete_composed_index(model, fields, {'inde... | diff --git a/django/db/backends/base/schema.py b/django/db/backends/base/schema.py
--- a/django/db/backends/base/schema.py
+++ b/django/db/backends/base/schema.py
@@ -393,7 +393,12 @@ def alter_index_together(self, model, old_index_together, new_index_together):
news = {tuple(fields) for fields in new_index_to... | Structural Bugs | High | Reliability |
django/django | 11,820 | Model ordering validation incorrectly rejects valid lookup segments, raising models.E015 for order_by paths ending in lookups like `isnull`. In `_check_ordering()`, the exception handler only allowed transforms:
```py
except (FieldDoesNotExist, AttributeError):
if fld is None or fld.get_transform(part) is None:
... | diff --git a/django/db/models/base.py b/django/db/models/base.py
--- a/django/db/models/base.py
+++ b/django/db/models/base.py
@@ -1747,7 +1747,9 @@ def _check_ordering(cls):
else:
_cls = None
except (FieldDoesNotExist, AttributeError):
- ... | Structural Bugs | Medium | Functional Suitability |
django/django | 4,349 | ExpressionWrapper incorrectly forces wrapped constant expressions into GROUP BY. When annotating with `ExpressionWrapper(Value(3), output_field=...)`, Django includes the wrapper in grouping instead of delegating to the inner expression, producing SQL like:
`... SELECT ..., 3 AS expr_res, SUM(...) ... GROUP BY ..., 3`
... | diff --git a/django/db/models/expressions.py b/django/db/models/expressions.py
--- a/django/db/models/expressions.py
+++ b/django/db/models/expressions.py
@@ -863,6 +863,9 @@ def set_source_expressions(self, exprs):
def get_source_expressions(self):
return [self.expression]
+ def get_group_by_cols(se... | Structural Bugs | High | Reliability |
django/django | 12,460 | Session encoding used the new Django 3.1 signing format even when `DEFAULT_HASHING_ALGORITHM='sha1'`, breaking interoperability with pre-3.1 instances. The buggy pattern was:
```py
def encode(self, session_dict):
return signing.dumps(session_dict, ...)
```
while `decode()` falls back to `_legacy_decode()` on fail... | diff --git a/django/contrib/sessions/backends/base.py b/django/contrib/sessions/backends/base.py
--- a/django/contrib/sessions/backends/base.py
+++ b/django/contrib/sessions/backends/base.py
@@ -108,6 +108,9 @@ def _hash(self, value):
def encode(self, session_dict):
"Return the given session dictionary ... | Interface, Integration, and System Bugs | High | Compatibility |
django/django | 6,744 | TruncDate/TruncTime ignore the caller-provided `tzinfo` and always use the global current timezone when generating SQL. In `as_sql()` they hardcode:
```py
tzname = timezone.get_current_timezone_name() if settings.USE_TZ else None
sql = connection.ops.datetime_cast_date_sql(lhs, tzname)
```
(and similarly for `datetim... | diff --git a/django/db/models/functions/datetime.py b/django/db/models/functions/datetime.py
--- a/django/db/models/functions/datetime.py
+++ b/django/db/models/functions/datetime.py
@@ -292,7 +292,7 @@ class TruncDate(TruncBase):
def as_sql(self, compiler, connection):
# Cast to date rather than truncate... | Structural Bugs | Medium | Functional Suitability |
django/django | 11,916 | Reassigning a pickled `Query` to a new `QuerySet` fails to restore the `values()/values_list()` iteration mode, so the queryset is evaluated as model instances instead of dict/tuple rows. The setter only did:
```py
@query.setter
def query(self, value):
self._query = value
```
After `prices2.query = unpickled_quer... | diff --git a/django/db/models/query.py b/django/db/models/query.py
--- a/django/db/models/query.py
+++ b/django/db/models/query.py
@@ -210,6 +210,8 @@ def query(self):
@query.setter
def query(self, value):
+ if value.values_select:
+ self._iterable_class = ValuesIterable
self._que... | Structural Bugs | High | Reliability |
django/django | 2,442 | The POSIX `lock()` implementation incorrectly treats `fcntl.flock()` as returning a status code, so it always reports failure. It does:
```py
ret = fcntl.flock(_fd(f), flags)
return ret == 0
```
but `fcntl.flock()` returns `None` on success and raises (e.g. `BlockingIOError`/`OSError`) on failure, so `ret == 0` is al... | diff --git a/django/core/files/locks.py b/django/core/files/locks.py
--- a/django/core/files/locks.py
+++ b/django/core/files/locks.py
@@ -107,9 +107,12 @@ def unlock(f):
return True
else:
def lock(f, flags):
- ret = fcntl.flock(_fd(f), flags)
- return ret == 0
+ ... | Structural Bugs | Medium | Functional Suitability |
django/django | 13,473 | `order_by('?')` incorrectly breaks aggregations by forcing the random ordering expression into `GROUP BY`. The compiler treats non-aggregate `ORDER BY` expressions as grouping columns, so `Random()` contributes group-by cols:
```sql
... COUNT(related.id) AS rc
... GROUP BY thing.id, RANDOM()
ORDER BY RANDOM()
```
Thi... | diff --git a/django/db/models/functions/math.py b/django/db/models/functions/math.py
--- a/django/db/models/functions/math.py
+++ b/django/db/models/functions/math.py
@@ -154,6 +154,9 @@ def as_oracle(self, compiler, connection, **extra_context):
def as_sqlite(self, compiler, connection, **extra_context):
... | Structural Bugs | Medium | Functional Suitability |
django/django | 12,076 | `dateformat.y()` incorrectly derives the 2‑digit year by slicing the year string, which drops leading zeros for years < 1000. Problematic code:
```python
def y(self):
return str(self.data.year)[2:]
```
For `year=123`, `str(123)[2:]` returns `'3'` instead of `'23'`, and for `year=9` returns `''`. This produces inc... | diff --git a/django/utils/dateformat.py b/django/utils/dateformat.py
--- a/django/utils/dateformat.py
+++ b/django/utils/dateformat.py
@@ -325,8 +325,8 @@ def W(self):
return self.data.isocalendar()[1]
def y(self):
- "Year, 2 digits; e.g. '99'"
- return str(self.data.year)[2:]
+ """... | Structural Bugs | Medium | Functional Suitability |
django/django | 12,414 | SQLite constraint checking builds PRAGMA/SELECT SQL by string-interpolating unquoted identifiers, so reserved-word table names (e.g., `order`) produce invalid SQL and crash `loaddata`. Problematic code:
`cursor.execute('PRAGMA foreign_key_check(%s)' % table_name)`
`cursor.execute('PRAGMA foreign_key_list(%s)' % table_... | diff --git a/django/db/backends/sqlite3/base.py b/django/db/backends/sqlite3/base.py
--- a/django/db/backends/sqlite3/base.py
+++ b/django/db/backends/sqlite3/base.py
@@ -327,19 +327,24 @@ def check_constraints(self, table_names=None):
violations = cursor.execute('PRAGMA foreign_key_check').fetchal... | Interface, Integration, and System Bugs | High | Compatibility |
django/django | 8,819 | `get_child_arguments()` incorrectly detects `python -m …` invocations by comparing `sys.argv[0]` to `django.__main__.__file__`, hard-coding Django and relying on `__file__` being set:
```py
import django.__main__
django_main_path = Path(django.__main__.__file__)
if Path(sys.argv[0]) == django_main_path:
args += ['... | diff --git a/django/utils/autoreload.py b/django/utils/autoreload.py
--- a/django/utils/autoreload.py
+++ b/django/utils/autoreload.py
@@ -216,14 +216,14 @@ def get_child_arguments():
executable is reported to not have the .exe extension which can cause bugs
on reloading.
"""
- import django.__main__
... | Structural Bugs | Medium | Functional Suitability |
django/django | 13,179 | Django’s model check incorrectly emits W042 for models inheriting a manually defined primary key via multi-table inheritance. `_check_default_pk()` only tested `cls._meta.pk.auto_created`, so inherited parent-link PKs (implemented as an auto-created `OneToOneField`) were treated as “auto-created default PKs”:
```py
if... | diff --git a/django/db/models/base.py b/django/db/models/base.py
--- a/django/db/models/base.py
+++ b/django/db/models/base.py
@@ -1299,6 +1299,11 @@ def check(cls, **kwargs):
def _check_default_pk(cls):
if (
cls._meta.pk.auto_created and
+ # Inherited PKs are checked in parents mo... | Structural Bugs | Low | Functional Suitability |
django/django | 11,003 | ModelChoiceField raises `ValidationError` for invalid selections without including the invalid input value in the error context, unlike other ChoiceField variants. In `to_python()`, it did:
```python
except (ValueError, TypeError, self.queryset.model.DoesNotExist):
raise ValidationError(self.error_messages['invali... | diff --git a/django/forms/models.py b/django/forms/models.py
--- a/django/forms/models.py
+++ b/django/forms/models.py
@@ -1284,7 +1284,11 @@ def to_python(self, value):
value = getattr(value, key)
value = self.queryset.get(**{key: value})
except (ValueError, TypeError, self.query... | Requirements, Features, and Functionality Bugs | Low | Usability |
django/django | 9,983 | INSERT paths returning `returning_fields` bypass field DB converters, so `from_db_value()` isn’t applied to returned PK/columns. The compiler returned raw cursor values directly:
```py
return self.connection.ops.fetch_returned_insert_rows(cursor)
# or
return [self.connection.ops.fetch_returned_insert_columns(cursor, s... | diff --git a/django/db/models/sql/compiler.py b/django/db/models/sql/compiler.py
--- a/django/db/models/sql/compiler.py
+++ b/django/db/models/sql/compiler.py
@@ -1405,6 +1405,7 @@ def execute_sql(self, returning_fields=None):
returning_fields and len(self.query.objs) != 1 and
not self.connect... | Structural Bugs | Medium | Functional Suitability |
django/django | 6,507 | HashedFilesMixin.post_process() incorrectly yields the same original file multiple times across multi-pass processing. The code unconditionally yielded every pass result:
```py
for name, hashed_name, processed, _ in self._post_process(...):
yield name, hashed_name, processed
...
for ... in range(...):
for name... | diff --git a/django/contrib/staticfiles/storage.py b/django/contrib/staticfiles/storage.py
--- a/django/contrib/staticfiles/storage.py
+++ b/django/contrib/staticfiles/storage.py
@@ -226,17 +226,25 @@ def post_process(self, paths, dry_run=False, **options):
path for path in paths
if matches_pa... | Structural Bugs | Medium | Functional Suitability |
django/django | 7,517 | Q.deconstruct() incorrectly special-cases single-child Q objects by assuming the lone child is a 2-tuple key/value pair. In `django/db/models/query_utils.py`:
```py
if len(self.children) == 1 and not isinstance(self.children[0], Q):
child = self.children[0]
kwargs = {child[0]: child[1]}
```
When the child is ... | diff --git a/django/db/models/query_utils.py b/django/db/models/query_utils.py
--- a/django/db/models/query_utils.py
+++ b/django/db/models/query_utils.py
@@ -84,14 +84,10 @@ def deconstruct(self):
path = '%s.%s' % (self.__class__.__module__, self.__class__.__name__)
if path.startswith('django.db.mode... | Structural Bugs | Medium | Reliability |
django/django | 10,680 | AutoFieldMeta.__subclasscheck__ incorrectly tests membership instead of inheritance, rejecting custom AutoField subclasses. The code used:
```py
def __subclasscheck__(self, subclass):
return subclass in self._subclasses or super().__subclasscheck__(subclass)
```
`_subclasses` contains concrete classes (e.g., BigA... | diff --git a/django/db/models/fields/__init__.py b/django/db/models/fields/__init__.py
--- a/django/db/models/fields/__init__.py
+++ b/django/db/models/fields/__init__.py
@@ -2524,7 +2524,7 @@ def __instancecheck__(self, instance):
return isinstance(instance, self._subclasses) or super().__instancecheck__(inst... | Structural Bugs | High | Functional Suitability |
django/django | 13,837 | Autoreloader reconstructs `python -m` invocations using `__main__.__spec__.parent`, truncating dotted module names. Problematic code:
```py
if __main__.__spec__.parent:
args += ['-m', __main__.__spec__.parent]
```
For `python -m foo.bar.baz`, `spec.parent` is `foo.bar`, so the child process is restarted as `-m fo... | diff --git a/django/utils/autoreload.py b/django/utils/autoreload.py
--- a/django/utils/autoreload.py
+++ b/django/utils/autoreload.py
@@ -223,8 +223,13 @@ def get_child_arguments():
# __spec__ is set when the server was started with the `-m` option,
# see https://docs.python.org/3/reference/import.html#main-... | Structural Bugs | Medium | Functional Suitability |
django/django | 8,433 | `RelatedIn` lookups with a queryset RHS inside an `OR` incorrectly propagate the RHS subquery’s default select list into `GROUP BY`, producing multi-column subqueries. Problematic pattern: `Q(agent__property_groups__in=property_groups) | Q(agent__property_groups__count=0)` generates `SELECT U0."id", U0."created", ...` ... | diff --git a/django/db/models/lookups.py b/django/db/models/lookups.py
--- a/django/db/models/lookups.py
+++ b/django/db/models/lookups.py
@@ -406,6 +406,15 @@ def process_rhs(self, compiler, connection):
self.rhs.add_fields(['pk'])
return super().process_rhs(compiler, connection)
+ d... | Structural Bugs | High | Reliability |
django/django | 13,134 | catch_all_view() builds its APPEND_SLASH redirect using `request.path_info`, dropping any `FORCE_SCRIPT_NAME`/script prefix. Problematic code:
```py
path = '%s/' % request.path_info
return HttpResponsePermanentRedirect(path)
```
`path_info` excludes the script name, so when Django is mounted under a subpath, the redi... | diff --git a/django/contrib/admin/sites.py b/django/contrib/admin/sites.py
--- a/django/contrib/admin/sites.py
+++ b/django/contrib/admin/sites.py
@@ -420,14 +420,13 @@ def autocomplete_view(self, request):
def catch_all_view(self, request, url):
if settings.APPEND_SLASH and not url.endswith('/'):
... | Interface, Integration, and System Bugs | Medium | Compatibility |
django/django | 14,053 | ManifestStaticFilesStorage.post_process() can crash when max_post_process_passes is 0 because `substitutions` is only assigned inside the loop and then referenced afterward. Problematic pattern:
```py
for i in range(self.max_post_process_passes):
substitutions = False
...
if substitutions:
...
```
With `m... | diff --git a/django/contrib/staticfiles/storage.py b/django/contrib/staticfiles/storage.py
--- a/django/contrib/staticfiles/storage.py
+++ b/django/contrib/staticfiles/storage.py
@@ -260,6 +260,7 @@ def post_process(self, paths, dry_run=False, **options):
processed_adjustable_paths[name] = (name, hashe... | Structural Bugs | High | Reliability |
django/django | 6,498 | BoundWidget.id_for_label hardcodes a generated ID and ignores the widget-provided `attrs['id']`, breaking label/checkbox association when `auto_id` or ChoiceWidget options set custom IDs. Problematic code:
```py
def id_for_label(self):
return 'id_%s_%s' % (self.data['name'], self.data['index'])
```
But `BoundFiel... | diff --git a/django/forms/boundfield.py b/django/forms/boundfield.py
--- a/django/forms/boundfield.py
+++ b/django/forms/boundfield.py
@@ -277,7 +277,7 @@ def template_name(self):
@property
def id_for_label(self):
- return 'id_%s_%s' % (self.data['name'], self.data['index'])
+ return self.data... | Structural Bugs | Medium | Functional Suitability |
django/django | 11,276 | trim_punctuation() miscomputes how much to trim when the URL contains HTML-escaped sequences, causing trailing punctuation removal to slice the wrong part of the original string. It used unescaped lengths to index the escaped string:
`trail = middle[len(stripped):] + trail`
`middle = middle[:len(stripped) - len(middle... | diff --git a/django/utils/html.py b/django/utils/html.py
--- a/django/utils/html.py
+++ b/django/utils/html.py
@@ -283,8 +283,9 @@ def trim_punctuation(lead, middle, trail):
middle_unescaped = html.unescape(middle)
stripped = middle_unescaped.rstrip(TRAILING_PUNCTUATION_CHARS)
if ... | Structural Bugs | Medium | Functional Suitability |
django/django | 13,484 | ManyToManyRel.identity included `through_fields` without normalizing it to a hashable type, so lists in `through_fields` made the relation unhashable. Problematic code:
```py
return super().identity + (
self.through,
self.through_fields, # can be a list
self.db_constraint,
)
```
Since `__hash__` does `ha... | diff --git a/django/db/models/fields/reverse_related.py b/django/db/models/fields/reverse_related.py
--- a/django/db/models/fields/reverse_related.py
+++ b/django/db/models/fields/reverse_related.py
@@ -310,7 +310,7 @@ def __init__(self, field, to, related_name=None, related_query_name=None,
def identity(self):
... | Structural Bugs | High | Reliability |
django/django | 10,091 | method_decorator() passes a `functools.partial` as the decorated callable, losing function metadata required by decorators using `functools.wraps`. In `_wrapper()` it builds:
```py
bound_method = partial(method.__get__(self, type(self)))
```
`partial` lacks `__name__`, `__module__`, etc., so a decorator like:
```py
... | diff --git a/django/utils/decorators.py b/django/utils/decorators.py
--- a/django/utils/decorators.py
+++ b/django/utils/decorators.py
@@ -37,7 +37,7 @@ def _wrapper(self, *args, **kwargs):
# 'self' argument, but it's a closure over self so it can call
# 'func'. Also, wrap method.__get__() in a functi... | Structural Bugs | High | Functional Suitability |
django/django | 12,343 | get_admin_url generates incorrect admin links for readonly ForeignKey fields in a custom AdminSite because it reverses URLs without scoping to the current admin namespace. The code uses:
`url = reverse(url_name, args=[quote(remote_obj.pk)])`
Without `current_app`, Django resolves `url_name` against the default `admin... | diff --git a/django/contrib/admin/helpers.py b/django/contrib/admin/helpers.py
--- a/django/contrib/admin/helpers.py
+++ b/django/contrib/admin/helpers.py
@@ -209,7 +209,11 @@ def get_admin_url(self, remote_field, remote_obj):
remote_field.model._meta.model_name,
)
try:
- url =... | Interface, Integration, and System Bugs | Medium | Compatibility |
django/django | 12,088 | ModelChoiceIteratorValue instances are unhashable, breaking dict/set membership when widget option values are used as keys. In Django 3.1, `create_option()` receives `value` as a `ModelChoiceIteratorValue`, so code like `if value in self.show_fields:` fails with `TypeError: unhashable type: 'ModelChoiceIteratorValue'`.... | diff --git a/django/forms/models.py b/django/forms/models.py
--- a/django/forms/models.py
+++ b/django/forms/models.py
@@ -1166,6 +1166,9 @@ def __init__(self, value, instance):
def __str__(self):
return str(self.value)
+ def __hash__(self):
+ return hash(self.value)
+
def __eq__(self, ot... | Data Bugs | High | Functional Suitability |
django/django | 3,484 | RenameModel.database_forwards always calls `schema_editor.alter_db_table()` even when both models explicitly use the same `db_table`, causing an unnecessary “rename” of an unchanged table. Problematic code:
```py
schema_editor.alter_db_table(
new_model,
old_model._meta.db_table,
new_model._meta.db_table,
)... | diff --git a/django/db/migrations/operations/models.py b/django/db/migrations/operations/models.py
--- a/django/db/migrations/operations/models.py
+++ b/django/db/migrations/operations/models.py
@@ -320,12 +320,13 @@ def database_forwards(self, app_label, schema_editor, from_state, to_state):
new_model = to_st... | Structural Bugs | Medium | Reliability |
django/django | 7,132 | inspectdb incorrectly assumes all foreign keys reference the target table’s primary key, ignoring foreign keys to non-PK unique columns. The buggy pattern uses only the referenced table name:
```py
rel_to = "self" if relations[column_name][1] == table_name else table2model(relations[column_name][1])
field_type = 'Fore... | diff --git a/django/core/management/commands/inspectdb.py b/django/core/management/commands/inspectdb.py
--- a/django/core/management/commands/inspectdb.py
+++ b/django/core/management/commands/inspectdb.py
@@ -116,13 +116,17 @@ def table2model(table_name):
extra_params['unique'] = True
... | Structural Bugs | Medium | Functional Suitability |
django/django | 12,771 | The migration autodetector assumes every relational field deconstruction includes a `'to'` kwarg and unconditionally deletes it, causing a `KeyError` for custom fields that omit `'to'` in `deconstruct()`. Problematic code:
```py
deconstruction = self.deep_deconstruct(field)
if field.remote_field and field.remote_field... | diff --git a/django/db/migrations/autodetector.py b/django/db/migrations/autodetector.py
--- a/django/db/migrations/autodetector.py
+++ b/django/db/migrations/autodetector.py
@@ -96,7 +96,7 @@ def only_relation_agnostic_fields(self, fields):
for name, field in sorted(fields.items()):
deconstructio... | Structural Bugs | Medium | Reliability |
django/django | 2,145 | LEVEL_TAGS is initialized once and never refreshed when MESSAGE_TAGS is overridden in tests, so Message.level_tag can become stale/empty. The code relies on a module-level cache:
```py
# django.contrib.messages.storage.base
LEVEL_TAGS = get_level_tags()
```
When `@override_settings(MESSAGE_TAGS=...)` runs, `base.LEVE... | diff --git a/django/contrib/messages/apps.py b/django/contrib/messages/apps.py
--- a/django/contrib/messages/apps.py
+++ b/django/contrib/messages/apps.py
@@ -1,7 +1,18 @@
from django.apps import AppConfig
+from django.contrib.messages.storage import base
+from django.contrib.messages.utils import get_level_tags
+from... | Interface, Integration, and System Bugs | Medium | Functional Suitability |
django/django | 13,207 | CharField unconditionally adds a MaxLengthValidator even when max_length is None, producing an invalid validator and runtime errors. Problematic code:
```py
self.validators.append(validators.MaxLengthValidator(self.max_length))
```
When Value._resolve_output_field() returns `fields.CharField()` for string literals, m... | diff --git a/django/db/models/fields/__init__.py b/django/db/models/fields/__init__.py
--- a/django/db/models/fields/__init__.py
+++ b/django/db/models/fields/__init__.py
@@ -1010,7 +1010,8 @@ class CharField(Field):
def __init__(self, *args, db_collation=None, **kwargs):
super().__init__(*args, **kwargs)... | Structural Bugs | Medium | Reliability |
django/django | 5,318 | Reverse prefetch was overwriting an already-prefetched parent instance, causing deferred-field state to leak from the outer queryset. In `get_prefetch_queryset()`, Django unconditionally did:
```py
instance = instances_dict[rel_obj_attr(rel_obj)]
setattr(rel_obj, self.field.name, instance)
```
When `Profile.objects.p... | diff --git a/django/db/models/fields/related_descriptors.py b/django/db/models/fields/related_descriptors.py
--- a/django/db/models/fields/related_descriptors.py
+++ b/django/db/models/fields/related_descriptors.py
@@ -646,8 +646,9 @@ def get_prefetch_queryset(self, instances, queryset=None):
# Since we ju... | Interface, Integration, and System Bugs | Medium | Performance Efficiency |
django/django | 14,026 | Aggregates with `default=` lose their summary flag when wrapped in `Coalesce`, producing invalid SQL after `annotate()`.
Problematic pattern in `Aggregate.resolve_expression()`:
```py
c.default = None
return Coalesce(c, default, output_field=c._output_field_or_none)
```
`Coalesce(...)` isn’t marked as a summary (`is_s... | diff --git a/django/db/models/aggregates.py b/django/db/models/aggregates.py
--- a/django/db/models/aggregates.py
+++ b/django/db/models/aggregates.py
@@ -65,7 +65,9 @@ def resolve_expression(self, query=None, allow_joins=True, reuse=None, summarize
if hasattr(default, 'resolve_expression'):
defau... | Structural Bugs | High | Reliability |
django/django | 6,478 | Negated `Exists` expressions crash SQL compilation when the subquery is empty, causing the entire WHERE clause to be dropped/short-circuited. In `Exists.as_sql()`, the code blindly compiles `query = self.query.exists(...)`:
```py
sql, params = super().as_sql(..., query=query, ...)
```
If `self.query` is `MyModel.obje... | diff --git a/django/db/models/expressions.py b/django/db/models/expressions.py
--- a/django/db/models/expressions.py
+++ b/django/db/models/expressions.py
@@ -1211,13 +1211,18 @@ def __invert__(self):
def as_sql(self, compiler, connection, template=None, **extra_context):
query = self.query.exists(using... | Structural Bugs | High | Functional Suitability |
django/django | 5,090 | RegisterLookupMixin._unregister_lookup() removes a lookup from `class_lookups` but leaves the per-class lookup cache stale. The method only does:
```py
del cls.class_lookups[lookup_name]
```
Unlike `register_lookup()`, it doesn’t call `_clear_cached_lookups()`. As a result, subsequent lookup resolution can still use ... | diff --git a/django/db/models/query_utils.py b/django/db/models/query_utils.py
--- a/django/db/models/query_utils.py
+++ b/django/db/models/query_utils.py
@@ -217,6 +217,7 @@ def _unregister_lookup(cls, lookup, lookup_name=None):
if lookup_name is None:
lookup_name = lookup.lookup_name
de... | Structural Bugs | Medium | Reliability |
django/django | 12,928 | Autoreload incorrectly treats empty template directory entries as valid paths, causing template change detection to always trigger. In `get_template_directories()`, the code unconditionally normalizes and joins dirs:
```py
items.update(cwd / to_path(dir) for dir in backend.engine.dirs)
...
for directory in loader.get_... | diff --git a/django/template/autoreload.py b/django/template/autoreload.py
--- a/django/template/autoreload.py
+++ b/django/template/autoreload.py
@@ -17,7 +17,7 @@ def get_template_directories():
if not isinstance(backend, DjangoTemplates):
continue
- items.update(cwd / to_path(dir) for ... | Structural Bugs | Medium | Reliability |
django/django | 15,677 | RenameIndex.database_forwards() attempts to rename an index even when the resolved “old” index name already equals the target name, causing duplicate index creation on re-apply. Problematic pattern:
```py
old_index = from_model_state.get_index_by_name(self.old_name)
# ... no equality check ...
new_index = to_model_sta... | diff --git a/django/db/migrations/operations/models.py b/django/db/migrations/operations/models.py
--- a/django/db/migrations/operations/models.py
+++ b/django/db/migrations/operations/models.py
@@ -960,6 +960,9 @@ def database_forwards(self, app_label, schema_editor, from_state, to_state):
else:
... | Structural Bugs | High | Reliability |
django/django | 14,832 | floatformat loses Decimal precision by converting Decimals via `repr()`, which yields a float-like representation. The code does:
```python
input_val = repr(text)
d = Decimal(input_val)
```
For `Decimal('42.12345678901234567890')`, `repr()` can produce a rounded value (e.g., `Decimal('42.123456789012344')`), so `Deci... | diff --git a/django/template/defaultfilters.py b/django/template/defaultfilters.py
--- a/django/template/defaultfilters.py
+++ b/django/template/defaultfilters.py
@@ -149,7 +149,7 @@ def floatformat(text, arg=-1):
use_l10n = False
arg = arg[:-1] or -1
try:
- input_val = repr(text)
... | Structural Bugs | Medium | Functional Suitability |
django/django | 6,338 | Case/When renders invalid SQL when the condition compiles to an empty string (match-all), e.g. `When(~Q(pk__in=[]), then=Value(True))`. The compiler produces `condition_sql == ""`, yielding `CASE WHEN THEN true ...`:
`ORDER BY CASE WHEN THEN True ELSE False END`
This is a bug because Django treats match-all filters a... | diff --git a/django/db/models/expressions.py b/django/db/models/expressions.py
--- a/django/db/models/expressions.py
+++ b/django/db/models/expressions.py
@@ -1299,6 +1299,11 @@ def as_sql(self, compiler, connection, template=None, **extra_context):
template_params = extra_context
sql_params = []
... | Structural Bugs | High | Reliability |
django/django | 2,106 | The duplicate fixture directory check compares a string path against a list that may contain `Path` objects, so duplicates are missed. In `fixture_dirs()`:
```py
app_dir = os.path.join(app_config.path, "fixtures")
if app_dir in fixture_dirs:
```
When `settings.FIXTURE_DIRS` includes `Path(...)`, `app_dir` (a `str`) i... | diff --git a/django/core/management/commands/loaddata.py b/django/core/management/commands/loaddata.py
--- a/django/core/management/commands/loaddata.py
+++ b/django/core/management/commands/loaddata.py
@@ -367,7 +367,7 @@ def fixture_dirs(self):
for app_config in apps.get_app_configs():
app_label... | Data Bugs | Medium | Reliability |
django/django | 15,271 | MOD-combined numeric expressions fail to resolve the correct `output_field` because `Combinable.MOD` is omitted from the numeric type-resolution operator set. The resolver only treats these as numeric:
```python
(Combinable.ADD, Combinable.SUB, Combinable.MUL, Combinable.DIV)
```
so `%` falls back to default/incorrec... | diff --git a/django/db/models/expressions.py b/django/db/models/expressions.py
--- a/django/db/models/expressions.py
+++ b/django/db/models/expressions.py
@@ -533,6 +533,7 @@ def __hash__(self):
Combinable.SUB,
Combinable.MUL,
Combinable.DIV,
+ Combinable.MOD,
... | Structural Bugs | Medium | Functional Suitability |
django/django | 14,068 | `Sitemap.get_latest_lastmod()` crashes for empty sitemaps when `lastmod` is callable because it calls `max()` on an empty list:
```py
return max([self.lastmod(item) for item in self.items()])
```
If `self.items()` yields no items, `max([])` raises `ValueError: max() arg is an empty sequence`, causing the sitemap inde... | diff --git a/django/contrib/sitemaps/__init__.py b/django/contrib/sitemaps/__init__.py
--- a/django/contrib/sitemaps/__init__.py
+++ b/django/contrib/sitemaps/__init__.py
@@ -167,7 +167,7 @@ def get_latest_lastmod(self):
return None
if callable(self.lastmod):
try:
- ret... | Structural Bugs | Medium | Reliability |
django/django | 16,027 | timesince() constructs a “pivot” datetime without preserving timezone info, producing a naive datetime that’s later subtracted from an aware datetime when USE_TZ=True. Problematic code:
```py
pivot = datetime.datetime(d.year, d.month, d.day, d.hour, d.minute, d.second)
```
If `d` is timezone-aware and the interval is... | diff --git a/django/utils/timesince.py b/django/utils/timesince.py
--- a/django/utils/timesince.py
+++ b/django/utils/timesince.py
@@ -97,6 +97,7 @@ def timesince(d, now=None, reversed=False, time_strings=None, depth=2):
d.hour,
d.minute,
d.second,
+ tzinfo=d.tzinfo,
... | Data Bugs | High | Reliability |
django/django | 13,134 | AdminSite.catch_all_view() builds APPEND_SLASH redirects using only the path, dropping the query string. The code:
```py
return HttpResponsePermanentRedirect("%s/" % request.path)
```
ignores `request.META['QUERY_STRING']`, so `/admin/auth/foo?id=123` redirects to `/admin/auth/foo/` instead of `/admin/auth/foo/?id=12... | diff --git a/django/contrib/admin/sites.py b/django/contrib/admin/sites.py
--- a/django/contrib/admin/sites.py
+++ b/django/contrib/admin/sites.py
@@ -453,7 +453,9 @@ def catch_all_view(self, request, url):
pass
else:
if getattr(match.func, "should_append_slash", True):
- ... | Structural Bugs | Medium | Functional Suitability |
django/django | 7,377 | makemigrations performs router consistency checks using mismatched (app_label, model) pairs by iterating models across the whole project for each app. The buggy pattern is:
```py
for app_label in consistency_check_labels
for model in apps.get_models(app_label)
```
`apps.get_models(app_label)` doesn’t scope to that ap... | diff --git a/django/core/management/commands/makemigrations.py b/django/core/management/commands/makemigrations.py
--- a/django/core/management/commands/makemigrations.py
+++ b/django/core/management/commands/makemigrations.py
@@ -105,7 +105,7 @@ def handle(self, *app_labels, **options):
# At least... | Structural Bugs | Medium | Functional Suitability |
matplotlib/matplotlib | 8,638 | `Axes.hist()` drops the user-specified `range` when `density=True` because it overwrites the kwargs passed to `np.histogram`. The code does:
```python
hist_kwargs = dict(density=density)
```
replacing an existing `hist_kwargs` that already contained `range=range` (and other options). As a result, `np.histogram(..., d... | diff --git a/lib/matplotlib/axes/_axes.py b/lib/matplotlib/axes/_axes.py
--- a/lib/matplotlib/axes/_axes.py
+++ b/lib/matplotlib/axes/_axes.py
@@ -6686,7 +6686,7 @@ def hist(self, x, bins=None, range=None, density=None, weights=None,
density = bool(density) or bool(normed)
if density and not stacked... | Structural Bugs | Medium | Functional Suitability |
matplotlib/matplotlib | 17,636 | Log-scaled images could pass a non-positive vmin into `LogNorm`, causing intermittent `ValueError: Invalid vmin or vmax`. In `_make_image`, the vmin adjustment only handled strictly negative values:
```py
if isinstance(self.norm, mcolors.LogNorm):
if s_vmin < 0:
s_vmin = max(s_vmin, np.finfo(scaled_dtype).... | diff --git a/lib/matplotlib/image.py b/lib/matplotlib/image.py
--- a/lib/matplotlib/image.py
+++ b/lib/matplotlib/image.py
@@ -532,9 +532,9 @@ def _make_image(self, A, in_bbox, out_bbox, clip_bbox, magnification=1.0,
# we have re-set the vmin/vmax to account for small errors
# that may... | Structural Bugs | Medium | Reliability |
matplotlib/matplotlib | 20,113 | SpanSelector’s interactive edge handles were initialized with `self.extents`, which defaults to `(0, 0)`, causing Matplotlib to autoscale the axes to include 0. Problematic code:
```python
self._edge_handles = ToolLineHandles(self.ax, self.extents, ...)
```
Because `ToolLineHandles` creates artists at x/y=0, the axes... | diff --git a/lib/matplotlib/widgets.py b/lib/matplotlib/widgets.py
--- a/lib/matplotlib/widgets.py
+++ b/lib/matplotlib/widgets.py
@@ -2156,7 +2156,12 @@ def new_axes(self, ax):
self.artists.append(self._rect)
def _setup_edge_handle(self, props):
- self._edge_handles = ToolLineHandles(self.ax... | Structural Bugs | Medium | Functional Suitability |
matplotlib/matplotlib | 19,849 | Datetime tick labels wrapped for `usetex=True` were only protecting `-` from TeX math spacing, leaving other separators and spaces to be interpreted as math operators/whitespace, producing unclear spacing. In `_wrap_in_tex`:
```python
ret_text = '$\\mathdefault{'+ret_text.replace('-', '{-}')+'}$'
```
This fails to br... | diff --git a/lib/matplotlib/dates.py b/lib/matplotlib/dates.py
--- a/lib/matplotlib/dates.py
+++ b/lib/matplotlib/dates.py
@@ -595,8 +595,11 @@ def _wrap_in_tex(text):
p = r'([a-zA-Z]+)'
ret_text = re.sub(p, r'}$\1$\\mathdefault{', text)
- # Braces ensure dashes are not spaced like binary operators.
- ... | Structural Bugs | Low | Usability |
matplotlib/matplotlib | 20,054 | Colorbar divider segments are incorrectly sliced when `drawedges=True` with `extend='both'`, dropping the extremity edges. In `_add_solids`, dividers are set via:
```python
self.dividers.set_segments(np.dstack([X, Y])[1:-1])
```
This unconditional `[1:-1]` removes the first and last segment, which are required to dra... | diff --git a/lib/matplotlib/colorbar.py b/lib/matplotlib/colorbar.py
--- a/lib/matplotlib/colorbar.py
+++ b/lib/matplotlib/colorbar.py
@@ -651,8 +651,12 @@ def _add_solids(self, X, Y, C):
if not self.drawedges:
if len(self._y) >= self.n_rasterize:
self.solids.set_raste... | Structural Bugs | Low | Usability |
matplotlib/matplotlib | 12,909 | ConciseDateFormatter incorrectly suppresses the year offset for sub-year ranges when January isn’t present, because it disables the offset whenever the varying tick “level” is months/days:
```python
if len(np.unique(tickdate[:, level])) > 1:
if level < 2:
show_offset = False
```
This treats any month vari... | diff --git a/lib/matplotlib/dates.py b/lib/matplotlib/dates.py
--- a/lib/matplotlib/dates.py
+++ b/lib/matplotlib/dates.py
@@ -796,8 +796,10 @@ def format_ticks(self, values):
# mostly 0: years, 1: months, 2: days,
# 3: hours, 4: minutes, 5: seconds, 6: microseconds
for level in range(5, -1... | Structural Bugs | Medium | Usability |
matplotlib/matplotlib | 16,472 | `Axes3D.set_visible(False)` had no effect because `Axes3D.draw()` ignored the visibility flag and always rendered. The method lacked the standard early-exit guard:
```python
def draw(self, renderer):
self._unstale_viewLim()
# draw background patch ...
```
As a result, 3D subplots remained visible even when `a... | diff --git a/lib/mpl_toolkits/mplot3d/axes3d.py b/lib/mpl_toolkits/mplot3d/axes3d.py
--- a/lib/mpl_toolkits/mplot3d/axes3d.py
+++ b/lib/mpl_toolkits/mplot3d/axes3d.py
@@ -387,6 +387,8 @@ def apply_aspect(self, position=None):
@martist.allow_rasterization
def draw(self, renderer):
+ if not self.get_vi... | Structural Bugs | Medium | Functional Suitability |
matplotlib/matplotlib | 16,010 | Patch objects incorrectly discard the dash offset when drawing by forcibly zeroing it in `Patch.draw()`. The code wraps rendering with:
`with cbook._setattr_cm(self, _dash_pattern=(0, self._dash_pattern[1]))`
which overwrites any user-specified dash tuple `(offset, onoffseq)` to `(0, onoffseq)`. As a result, `ls=(10,... | diff --git a/lib/matplotlib/patches.py b/lib/matplotlib/patches.py
--- a/lib/matplotlib/patches.py
+++ b/lib/matplotlib/patches.py
@@ -586,9 +586,8 @@ def draw(self, renderer):
# docstring inherited
if not self.get_visible():
return
- # Patch has traditionally ignored the dashoffse... | Structural Bugs | Medium | Functional Suitability |
matplotlib/matplotlib | 23,751 | `Axes.bar` crashes when all x positions are non-finite because `_convert_dx` assumes `_safe_first_finite` will always find a finite element. In `_convert_dx`:
```python
x0 = cbook._safe_first_finite(x0)
x = cbook._safe_first_finite(xconv)
```
If `x0`/`xconv` are `[np.nan]`, `_safe_first_finite` raises `StopIteration... | diff --git a/lib/matplotlib/axes/_axes.py b/lib/matplotlib/axes/_axes.py
--- a/lib/matplotlib/axes/_axes.py
+++ b/lib/matplotlib/axes/_axes.py
@@ -2182,11 +2182,19 @@ def _convert_dx(dx, x0, xconv, convert):
x0 = cbook._safe_first_finite(x0)
except (TypeError, IndexError, KeyError):
... | Structural Bugs | High | Reliability |
matplotlib/matplotlib | 2,522 | `mlab._spectral_helper` incorrectly applies `np.abs` to the window when computing normalization/correction factors, e.g.:
```python
result = np.abs(result) / np.abs(window).sum()
result /= (np.abs(window)**2).sum()
result /= np.abs(window).sum()**2
```
Taking absolute values changes the effective window gain for window... | diff --git a/lib/matplotlib/mlab.py b/lib/matplotlib/mlab.py
--- a/lib/matplotlib/mlab.py
+++ b/lib/matplotlib/mlab.py
@@ -395,12 +395,12 @@ def _spectral_helper(x, y=None, NFFT=None, Fs=None, detrend_func=None,
elif mode == 'psd':
result = np.conj(result) * result
elif mode == 'magnitude':
- ... | Structural Bugs | Medium | Functional Suitability |
matplotlib/matplotlib | 14,948 | Axis offset/exponent text ignores `*tick.labelcolor` and is always colored from `*tick.color`. In `axis.py::_init`, `offsetText` is initialized with:
```python
self.offsetText.set(..., color=mpl.rcParams['xtick.color'])
# and
self.offsetText.set(..., color=mpl.rcParams['ytick.color'])
```
This bypasses `xtick.labelco... | diff --git a/lib/matplotlib/axis.py b/lib/matplotlib/axis.py
--- a/lib/matplotlib/axis.py
+++ b/lib/matplotlib/axis.py
@@ -2253,13 +2253,18 @@ def _init(self):
)
self.label_position = 'bottom'
+ if mpl.rcParams['xtick.labelcolor'] == 'inherit':
+ tick_color = mpl.rcParams['xtick.co... | Structural Bugs | Low | Usability |
matplotlib/matplotlib | 18,356 | `Figure.subfigures` ignores `wspace`/`hspace` because subfigures are instantiated without applying the `GridSpec`-computed positions when no layout engine is active. The code creates a `GridSpec` with spacing:
```python
gs = GridSpec(..., wspace=wspace, hspace=hspace, ...)
sfarr[j, i] = self.add_subfigure(gs[j, i], **... | diff --git a/lib/matplotlib/figure.py b/lib/matplotlib/figure.py
--- a/lib/matplotlib/figure.py
+++ b/lib/matplotlib/figure.py
@@ -1564,8 +1564,9 @@ def subfigures(self, nrows=1, ncols=1, squeeze=True,
wspace, hspace : float, default: None
The amount of width/height reserved for space between subf... | Structural Bugs | Medium | Functional Suitability |
matplotlib/matplotlib | 21,352 | `Axes.hexbin` applies an off-by-one threshold for `mincnt` when `C` is provided, filtering bins with exactly `mincnt` samples. In the `C is not None` path it used:
```python
reduce_C_function(acc) if len(acc) > mincnt else np.nan
```
so `mincnt=1` required `len(acc) >= 2`, unlike the `C is None` path which effectivel... | diff --git a/lib/matplotlib/axes/_axes.py b/lib/matplotlib/axes/_axes.py
--- a/lib/matplotlib/axes/_axes.py
+++ b/lib/matplotlib/axes/_axes.py
@@ -5014,7 +5014,7 @@ def reduce_C_function(C: array) -> float
if mincnt is None:
mincnt = 0
accum = np.array(
- [reduc... | Structural Bugs | Medium | Functional Suitability |
matplotlib/matplotlib | 1,931 | `twinx()`/`twiny()` fail to propagate axis unit converters to the twin axis, causing unit conversion to break and corrupt the original axis’ data limits. The twin is created without copying units:
```python
ax2 = ax1.twinx() # ax2.xaxis.units not set
ax2.plot(...) # triggers unit conversion/autoscale
```
With... | diff --git a/lib/matplotlib/axes/_base.py b/lib/matplotlib/axes/_base.py
--- a/lib/matplotlib/axes/_base.py
+++ b/lib/matplotlib/axes/_base.py
@@ -4441,6 +4441,7 @@ def twinx(self):
self.yaxis.tick_left()
ax2.xaxis.set_visible(False)
ax2.patch.set_visible(False)
+ ax2.xaxis.units = sel... | Interface, Integration, and System Bugs | Medium | Reliability |
matplotlib/matplotlib | 2,458 | `AnchoredLocatorBase.__call__` assumes a non-`None` renderer, but Matplotlib can invoke the axes locator with `renderer=None` during tight-bbox/layout, causing inset axes creation to crash. Problematic code:
```python
def __call__(self, ax, renderer):
self.axes = ax
bbox = self.get_window_extent(renderer)
```
... | diff --git a/lib/mpl_toolkits/axes_grid1/inset_locator.py b/lib/mpl_toolkits/axes_grid1/inset_locator.py
--- a/lib/mpl_toolkits/axes_grid1/inset_locator.py
+++ b/lib/mpl_toolkits/axes_grid1/inset_locator.py
@@ -69,6 +69,8 @@ def draw(self, renderer):
raise RuntimeError("No draw method should be called")
... | Structural Bugs | High | Reliability |
pallets/flask | 3,709 | Blueprints could be instantiated with an empty name, allowing invalid identifiers into routing/registration logic. The constructor lacked validation, e.g.:
```python
def __init__(..., name, ...):
...
if "." in name:
raise ValueError(...)
```
With `name == ""`, no exception was raised, so downstream co... | diff --git a/src/flask/blueprints.py b/src/flask/blueprints.py
--- a/src/flask/blueprints.py
+++ b/src/flask/blueprints.py
@@ -190,6 +190,9 @@ def __init__(
root_path=root_path,
)
+ if not name:
+ raise ValueError("'name' may not be empty.")
+
if "." in name:
... | Requirements, Features, and Functionality Bugs | Medium | Functional Suitability |
psf/requests | 789 | Digest authentication builds an invalid `Authorization` header by emitting an unquoted `qop` token. In `requests/auth.py`, the header is constructed as:
`base += ', qop=auth, nc=%s, cnonce="%s"' % (ncvalue, cnonce)`
RFC2617 requires `qop` to be a quoted-string, e.g. `qop="auth"`. Sending `qop=auth` can cause strict D... | diff --git a/requests/auth.py b/requests/auth.py
--- a/requests/auth.py
+++ b/requests/auth.py
@@ -105,7 +105,7 @@ def sha_utf8(x):
A1 = '%s:%s:%s' % (self.username, realm, self.password)
A2 = '%s:%s' % (method, path)
-
+
HA1 = hash_utf8(A1)
HA2 = hash_utf8(A2)
@@ -144,7 ... | Requirements, Features, and Functionality Bugs | Medium | Compatibility |
psf/requests | 3,789 | URLs with an empty DNS label (leading dot) bypass validation and trigger an uncaught IDNA encoding failure, raising `UnicodeError` instead of `InvalidURL`. The code only rejected wildcard hosts:
```py
elif host.startswith(u'*'):
raise InvalidURL('URL has an invalid label.')
```
So `http://.example.com` proceeds t... | diff --git a/requests/models.py b/requests/models.py
--- a/requests/models.py
+++ b/requests/models.py
@@ -403,7 +403,7 @@ def prepare_url(self, url, params):
host = self._get_idna_encoded_host(host)
except UnicodeError:
raise InvalidURL('URL has an invalid label.')
- ... | Structural Bugs | Medium | Reliability |
psf/requests | 1,924 | Proxy URLs containing credentials were incorrectly normalized because `prepend_scheme_if_needed()` dropped the `user:pass@` portion when rebuilding the netloc. The code used `parse_url()` output but only assigned `netloc` from host/port:
```python
if not netloc:
netloc, path = path, netloc
```
Since `parse_url` d... | diff --git a/requests/utils.py b/requests/utils.py
--- a/requests/utils.py
+++ b/requests/utils.py
@@ -974,6 +974,10 @@ def prepend_scheme_if_needed(url, new_scheme):
if not netloc:
netloc, path = path, netloc
+ if auth:
+ # parse_url doesn't provide the netloc with auth
+ # so we'll ad... | Structural Bugs | High | Functional Suitability |
pydata/xarray | 2,616 | combine_by_coords incorrectly enforces monotonicity on all coordinate dimensions, even those that are identical across inputs and not used for concatenation. The code iterates over every dimension in the combined result:
```python
for dim in concatenated.dims:
if dim in concatenated:
indexes = concatenated... | diff --git a/xarray/core/combine.py b/xarray/core/combine.py
--- a/xarray/core/combine.py
+++ b/xarray/core/combine.py
@@ -501,14 +501,13 @@ def combine_by_coords(datasets, compat='no_conflicts', data_vars='all',
fill_value=fill_value)
# Check the overall coordinates are m... | Structural Bugs | Medium | Functional Suitability |
pydata/xarray | 2,922 | Weighted reductions mis-handle boolean weights because `_sum_of_weights` computes the normalization via a dot/reduce on boolean arrays, yielding a boolean result instead of a count. Problematic code:
```python
mask = da.notnull()
sum_of_weights = self._reduce(mask, self.weights, dim=dim, skipna=False)
```
When `self.... | diff --git a/xarray/core/weighted.py b/xarray/core/weighted.py
--- a/xarray/core/weighted.py
+++ b/xarray/core/weighted.py
@@ -142,7 +142,14 @@ def _sum_of_weights(
# we need to mask data values that are nan; else the weights are wrong
mask = da.notnull()
- sum_of_weights = self._reduce(mask,... | Structural Bugs | Medium | Functional Suitability |
pydata/xarray | 1,597 | `DataArray.to_unstacked_dataset()` incorrectly selects per-variable slices without dropping the `variable_dim`, leaving a conflicting coordinate during `Dataset` construction. Problematic code:
```python
data_dict[k] = self.sel({variable_dim: k}).squeeze(drop=True)
```
`sel()` retains the `variable_dim` coordinate (e... | diff --git a/xarray/core/dataarray.py b/xarray/core/dataarray.py
--- a/xarray/core/dataarray.py
+++ b/xarray/core/dataarray.py
@@ -1961,7 +1961,7 @@ def to_unstacked_dataset(self, dim, level=0):
# pull variables out of datarray
data_dict = {}
for k in variables:
- data_dict[k] = se... | Structural Bugs | Medium | Functional Suitability |
pydata/xarray | 2,236 | `_maybe_null_out` incorrectly rejects `min_count` for multi-dimension reductions by raising on any iterable `axis`:
```python
if hasattr(axis, "__len__"):
raise ValueError("min_count is not available ...")
```
This prevents valid calls like `da.sum(["dim_0","dim_1"], min_count=1)` from working. Additionally, the ... | diff --git a/xarray/core/nanops.py b/xarray/core/nanops.py
--- a/xarray/core/nanops.py
+++ b/xarray/core/nanops.py
@@ -26,13 +26,9 @@ def _maybe_null_out(result, axis, mask, min_count=1):
"""
xarray version of pandas.core.nanops._maybe_null_out
"""
- if hasattr(axis, "__len__"): # if tuple or list
- ... | Structural Bugs | High | Functional Suitability |
pydata/xarray | 3,877 | `merge(combine_attrs="override")` returns the original attrs dict by reference, so the merged object shares mutable state with the first input. In `merge_attrs`:
```python
elif combine_attrs == "override":
return variable_attrs[0]
```
This reuses the same dict object, so mutating `merged.attrs` (e.g., `xds3.attrs... | diff --git a/xarray/core/merge.py b/xarray/core/merge.py
--- a/xarray/core/merge.py
+++ b/xarray/core/merge.py
@@ -501,7 +501,7 @@ def merge_attrs(variable_attrs, combine_attrs):
if combine_attrs == "drop":
return {}
elif combine_attrs == "override":
- return variable_attrs[0]
+ return ... | Structural Bugs | Medium | Reliability |
pydata/xarray | 1,496 | `xr.where(..., keep_attrs=True)` assumes the second argument `x` always contributes an attrs entry, but scalars don’t, causing an out-of-range access. The code sets:
```python
if keep_attrs is True:
keep_attrs = lambda attrs, context: attrs[1]
```
When `x` is a scalar (e.g., `1`), `apply_ufunc` provides fewer `at... | diff --git a/xarray/core/computation.py b/xarray/core/computation.py
--- a/xarray/core/computation.py
+++ b/xarray/core/computation.py
@@ -1825,11 +1825,10 @@ def where(cond, x, y, keep_attrs=None):
"""
if keep_attrs is None:
keep_attrs = _get_keep_attrs(default=False)
-
if keep_attrs is True:
... | Structural Bugs | Medium | Reliability |
pydata/xarray | 6,548 | `_ensure_numeric()` incorrectly converts `timedelta64` inputs using the datetime conversion path, producing huge numeric magnitudes and wrong `polyval` results. The buggy pattern was:
```py
if x.dtype.kind in "mM":
return x.copy(data=datetime_to_numeric(...))
```
This treats `dtype.kind == "m"` (timedelta) as dat... | diff --git a/xarray/core/computation.py b/xarray/core/computation.py
--- a/xarray/core/computation.py
+++ b/xarray/core/computation.py
@@ -1933,7 +1933,8 @@ def _ensure_numeric(data: T_Xarray) -> T_Xarray:
from .dataset import Dataset
def to_floatable(x: DataArray) -> DataArray:
- if x.dtype.kind in ... | Structural Bugs | High | Functional Suitability |
pydata/xarray | 5,900 | Dataset.chunks incorrectly forces materialization of lazily-backed variables by accessing `v.data`, which falls back to `v.values` and triggers `np.asarray` on the backend array. Problematic pattern:
```python
for v in variables:
if hasattr(v.data, "chunks"):
...
```
For non-dask lazy arrays (e.g., ZarrAr... | diff --git a/xarray/core/common.py b/xarray/core/common.py
--- a/xarray/core/common.py
+++ b/xarray/core/common.py
@@ -2023,7 +2023,7 @@ def get_chunksizes(
chunks: dict[Any, tuple[int, ...]] = {}
for v in variables:
- if hasattr(v.data, "chunks"):
+ if hasattr(v._data, "chunks"):
... | Structural Bugs | High | Performance Efficiency |
pydata/xarray | 4,219 | `DataArrayRolling.__iter__` computed window slices as right-aligned regardless of `center=True`, so manual iteration produced shifted windows. The iterator used:
```python
stops = np.arange(1, len(self.window_labels) + 1)
starts = stops - int(self.window[0])
starts[: int(self.window[0])] = 0
```
This ignores centerin... | diff --git a/xarray/core/rolling.py b/xarray/core/rolling.py
--- a/xarray/core/rolling.py
+++ b/xarray/core/rolling.py
@@ -267,16 +267,21 @@ def __init__(
# TODO legacy attribute
self.window_labels = self.obj[self.dim[0]]
- def __iter__(self) -> Iterator[tuple[RollingKey, DataArray]]:
+ def __... | Structural Bugs | Medium | Functional Suitability |
pydata/xarray | 5,636 | `PandasMultiIndexingAdapter.__array__` ignored the requested/underlying dtype for MultiIndex levels, causing int32 coordinates to be upcast to int64 during `stack()`. Problematic code:
```py
def __array__(self, dtype=None):
if self.level is not None:
return self.array.get_level_values(self.level).values
``... | diff --git a/xarray/core/indexing.py b/xarray/core/indexing.py
--- a/xarray/core/indexing.py
+++ b/xarray/core/indexing.py
@@ -1531,8 +1531,12 @@ def __init__(
self.level = level
def __array__(self, dtype: DTypeLike = None) -> np.ndarray:
+ if dtype is None:
+ dtype = self.dtype
... | Data Bugs | Medium | Functional Suitability |
pylint-dev/pylint | 6,098 | `pylint --jobs=0` can compute an invalid CPU count of 0 in Kubernetes cgroups, causing multiprocessing to crash. In `_query_cpu()`, CPU shares are converted to cores via integer truncation:
```py
cpu_shares = int(file.read().rstrip())
avail_cpu = int(cpu_shares / 1024) # e.g., 2/1024 -> 0
```
When `avail_cpu` become... | diff --git a/pylint/lint/run.py b/pylint/lint/run.py
--- a/pylint/lint/run.py
+++ b/pylint/lint/run.py
@@ -58,6 +58,13 @@ def _query_cpu() -> int | None:
cpu_shares = int(file.read().rstrip())
# For AWS, gives correct value * 1024.
avail_cpu = int(cpu_shares / 1024)
+
+ # In K8s Pods a... | Structural Bugs | High | Reliability |
pylint-dev/pylint | 4,164 | `modify_sys_path()` unconditionally removes the first `sys.path` entry, corrupting caller-provided import paths when `pylint` is executed via `runpy` with `alter_sys=True`. Problematic code:
```py
sys.path.pop(0)
```
This assumes `sys.path[0]` is the runpy-inserted CWD entry (`""`, `"."`, or `os.getcwd()`), but in em... | diff --git a/pylint/__init__.py b/pylint/__init__.py
--- a/pylint/__init__.py
+++ b/pylint/__init__.py
@@ -96,9 +96,10 @@ def modify_sys_path() -> None:
if pylint is installed in an editable configuration (as the last item).
https://github.com/PyCQA/pylint/issues/4161
"""
- sys.path.pop(0)
- en... | Structural Bugs | Medium | Reliability |
pytest-dev/pytest | 3,250 | Marker collection incorrectly relied on attribute lookup for `pytestmark`, so multiple inheritance lost base-class marks due to MRO shadowing. The buggy pattern was:
```python
mark_list = getattr(obj, "pytestmark", [])
```
For a class `TestDings(Foo, Bar)`, `getattr` returns only the first resolved `pytestmark` (e.g.... | diff --git a/src/_pytest/mark/structures.py b/src/_pytest/mark/structures.py
--- a/src/_pytest/mark/structures.py
+++ b/src/_pytest/mark/structures.py
@@ -355,12 +355,35 @@ def __call__(self, *args: object, **kwargs: object):
return self.with_args(*args, **kwargs)
-def get_unpacked_marks(obj: object) -> It... | Structural Bugs | Medium | Functional Suitability |
pytest-dev/pytest | 1,710 | pytest’s `num_mock_patch_args()` incorrectly tests `patch.new` against mock sentinels using membership, which triggers NumPy’s ambiguous truth-value error during collection. Problematic code:
```py
sentinels = [m.DEFAULT for m in mock_modules if m is not None]
[p for p in patchings if not p.attribute_name and p.new in... | diff --git a/src/_pytest/compat.py b/src/_pytest/compat.py
--- a/src/_pytest/compat.py
+++ b/src/_pytest/compat.py
@@ -64,13 +64,18 @@ def num_mock_patch_args(function):
patchings = getattr(function, "patchings", None)
if not patchings:
return 0
- mock_modules = [sys.modules.get("mock"), sys.modul... | Structural Bugs | High | Reliability |
pytest-dev/pytest | 4,965 | xdist report serialization dropped exception chaining, so only the final exception was reconstructed and displayed. The JSON conversion only serialized `reprtraceback`/`reprcrash`:
```py
d["longrepr"] = {"reprcrash": ..., "reprtraceback": ..., "sections": ...}
```
and `_from_json` always rebuilt a `ReprExceptionInfo`... | diff --git a/src/_pytest/reports.py b/src/_pytest/reports.py
--- a/src/_pytest/reports.py
+++ b/src/_pytest/reports.py
@@ -3,6 +3,7 @@
import py
+from _pytest._code.code import ExceptionChainRepr
from _pytest._code.code import ExceptionInfo
from _pytest._code.code import ReprEntry
from _pytest._code.code import... | Interface, Integration, and System Bugs | Medium | Usability |
pytest-dev/pytest | 1,795 | `pytest_runtest_makereport` incorrectly ties skip location rewriting to the `--runxfail` xfail-handling branch by using `elif`, so when `--runxfail` is enabled the skip fixup is skipped and the longrepr points to pytest internals.
Problematic pattern:
```py
elif (item._store.get(skipped_by_mark_key, True)
and r... | diff --git a/src/_pytest/skipping.py b/src/_pytest/skipping.py
--- a/src/_pytest/skipping.py
+++ b/src/_pytest/skipping.py
@@ -291,7 +291,8 @@ def pytest_runtest_makereport(item: Item, call: CallInfo[None]):
else:
rep.outcome = "passed"
rep.wasxfail = xfailed.reason
- e... | Structural Bugs | Medium | Usability |
YAML Metadata Warning:empty or missing yaml metadata in repo card
Check out the documentation for more information.
CR-Bench Dataset
Overview
This dataset contains the benchmarking data for the paper "CR-Bench: Evaluating the Real-World Utility of AI Code Review Agents" (arXiv:2603.11078). CR-Bench is a dataset designed to evaluate the reasoning and defect-detection capabilities of automated code review agents. It focuses on real-world, preventable defects, specifically targeting functional, performance, reliability, and security regressions rather than subjective stylistic changes.
Data Structure
The primary data is provided in a tabular format. For a visual reference of the data schema and a sample of the records, please refer to the included file verbatim: image_f2dd7e.png.
Schema Definitions
The dataset includes the following columns to provide comprehensive context and evaluation parameters for each defect:
repo: The source GitHub repository where the defect occurred (e.g.,astropy/astropy,django/django).bug_origin_pr: The specific pull request ID where the bug was originally introduced or identified.bug_description: A concise, technical description of the bug that focuses on the root cause rather than just the symptoms.correct_fix: The actualgit diffpatch containing the code changes required to resolve the defect.category: The root cause category of the bug (e.g., Structural Bugs, Interface, Integration, and System, Requirements, Features).severity: The critical level of the defect (e.g., Low, Medium, High).impact: The area of the software most affected by the defect (e.g., Functional Suitability, Reliability, Usability).
How to Use This Dataset
This dataset provides the essential metadata required to evaluate your AI code review agents. You will use the repo and bug_origin_pr columns to dynamically fetch the live pull request data via the GitHub REST API.
1. Fetching Pull Request Content
You can iterate through the dataset and use the GitHub API to retrieve either the PR metadata or the raw code diffs. Replace {repo} and {bug_origin_pr} with the corresponding values from the dataset (e.g., repo: astropy/astropy, bug_origin_pr: 6746).
To fetch PR metadata (JSON):
curl -H "Authorization: token $GITHUB_TOKEN" \
-H "Accept: application/vnd.github.v3+json" \
https://api.github.com/repos/{repo}/pulls/{bug_origin_pr}
To fetch the PR diff directly:
Note the custom Accept header which tells the GitHub API to return the diff instead of JSON.
curl -H "Authorization: token $GITHUB_TOKEN" \
-H "Accept: application/vnd.github.v3.diff" \
https://api.github.com/repos/{repo}/pulls/{bug_origin_pr}
2. Applying the Patch
The dataset is like SWE-Bench. So, the patch is in diff format which can be applied, and the repo can be containerized to get final results. Please switch to the commit ID of the base repo when the PR was raised for a proper testing.
- Downloads last month
- 21