]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
[3.13] gh-141805: Fix crash after concurrent addition objects with the same hash...
authorSerhiy Storchaka <storchaka@gmail.com>
Thu, 15 Jan 2026 07:59:15 +0000 (09:59 +0200)
committerGitHub <noreply@github.com>
Thu, 15 Jan 2026 07:59:15 +0000 (07:59 +0000)
This happens when the set contained several elements with the same hash,
and then some of them were removed.
(cherry picked from commit b8e925b4f8f6c5e28fbebc4f3965bf77610698b3)

Lib/test/test_set.py
Misc/NEWS.d/next/Core and Builtins/2026-01-13-22-26-49.gh-issue-141805.QzIKPS.rst [new file with mode: 0644]
Objects/setobject.c

index d9102eb98a54a673f74530c8b3f89b4637adf3df..2c2c8702b6c011adc65adc14845ecb80723ace83 100644 (file)
@@ -1813,6 +1813,7 @@ class TestWeirdBugs(unittest.TestCase):
         list(si)
 
     def test_merge_and_mutate(self):
+        # gh-141805
         class X:
             def __hash__(self):
                 return hash(0)
@@ -1825,6 +1826,33 @@ class TestWeirdBugs(unittest.TestCase):
         s = {0}
         s.update(other)
 
+    def test_hash_collision_concurrent_add(self):
+        class X:
+            def __hash__(self):
+                return 0
+        class Y:
+            flag = False
+            def __hash__(self):
+                return 0
+            def __eq__(self, other):
+                if not self.flag:
+                    self.flag = True
+                    s.add(X())
+                return self is other
+
+        a = X()
+        s = set()
+        s.add(a)
+        s.add(X())
+        s.remove(a)
+        # Now the set contains a dummy entry followed by an entry
+        # for an object with hash 0.
+        s.add(Y())
+        # The following operations should not crash.
+        repr(s)
+        list(s)
+        set() | s
+
 
 class TestOperationsMutating:
     """Regression test for bpo-46615"""
diff --git a/Misc/NEWS.d/next/Core and Builtins/2026-01-13-22-26-49.gh-issue-141805.QzIKPS.rst b/Misc/NEWS.d/next/Core and Builtins/2026-01-13-22-26-49.gh-issue-141805.QzIKPS.rst
new file mode 100644 (file)
index 0000000..8878d87
--- /dev/null
@@ -0,0 +1,3 @@
+Fix crash in :class:`set` when objects with the same hash are concurrently
+added to the set after removing an element with the same hash while the set
+still contains elements with the same hash.
index 5ec627558abbfe6c226ca526489177466b4d0be5..891987e3519966c20134ae3ed6e5e8dc93ddd376 100644 (file)
@@ -185,6 +185,9 @@ set_add_entry(PySetObject *so, PyObject *key, Py_hash_t hash)
   found_unused_or_dummy:
     if (freeslot == NULL)
         goto found_unused;
+    if (freeslot->hash != -1) {
+        goto restart;
+    }
     FT_ATOMIC_STORE_SSIZE_RELAXED(so->used, so->used + 1);
     freeslot->key = key;
     freeslot->hash = hash;