Skip to content
Closed
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 27 additions & 0 deletions Lib/test/test_set.py
Original file line number Diff line number Diff line change
Expand Up @@ -675,6 +675,33 @@ def __hash__(self):
with self.assertRaises(KeyError):
myset.discard(elem2)

def test_set_add_to_dummy_slot(self):
# gh-141805
tasks = set()

class Dummy:
def __hash__(self):
return 0

class CorruptTrigger:
triggered = False

def __hash__(self):
return 0

def __eq__(self, value):
if not self.triggered:
self.triggered = True
tasks.add(self)
return False

tasks.add(Dummy())
tasks.add(Dummy())
tasks.pop()
self.assertEqual(len(tasks), 1)
tasks.add(CorruptTrigger())
self.assertEqual(len(tasks), 2)
Comment thread
efimov-mikhail marked this conversation as resolved.


class SetSubclass(set):
pass
Expand Down
Comment thread
kemingy marked this conversation as resolved.
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Fix set length corruption when set additions occur within
Comment thread
efimov-mikhail marked this conversation as resolved.
Outdated
element comparison (:meth:`object.__eq__`) methods.
1 change: 1 addition & 0 deletions Objects/setobject.c
Original file line number Diff line number Diff line change
Expand Up @@ -298,6 +298,7 @@ set_add_entry_takeref(PySetObject *so, PyObject *key, Py_hash_t hash)
else if (entry->hash == -1) {
assert (entry->key == dummy);
freeslot = entry;
goto found_unused_or_dummy;
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No, this is incorrect.

Imagine you added two elements with the same hash, A and B. Then A hes been removed, and replaced with a dummy (this is why dummy is needed). Then we try to add B again. With your code, it will find a dummy in place of A, and replace it with B. Now you have two Bs in a set.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

#143781 adds a test for this.

}
entry++;
} while (probes--);
Expand Down
Loading