Method Absence (`AttributeError`) and Resizing During Iteration (`RuntimeError`) in `OrderedSet.intersection_update`
- Subsystem: Python Core Utilities (
openage/util/ordered_set.py) - Affected File:
openage/util/ordered_set.py, lines 83–94 - Severity: Medium-High (Unhandled Exceptions / Data Processing Failure)
Description & Root Cause
openage.util.ordered_set.OrderedSet defines an ordered set backed by a standard Python dictionary:
def intersection_update(self, other):
"""
Only keep elements that are both in self and other.
"""
keys_self = set(self.ordered_set.keys())
keys_other = set(other.keys())
intersection = keys_self & keys_other
for elem in self:
if elem not in intersection:
self.discard(elem)
This method exhibits two distinct fatal bugs:
-
Missing
.keys()method onOrderedSet: Line 88 callskeys_other = set(other.keys()). However,OrderedSetdoes not implement a.keys()method. Passing anotherOrderedSetinstance (the canonical usage pattern) fails immediately:AttributeError: 'OrderedSet' object has no attribute 'keys' -
Dictionary mutation during iteration: Even when
otheris adict(or an object providing.keys()), line 91 iterates overself:for elem in self:In Python,OrderedSet.__iter__returnsiter(self.ordered_set.keys()). Inside the loop, ifelem not in intersection,self.discard(elem)calls:self.ordered_set.pop(elem, -1)Mutating a dictionary while iterating over its keys raises:RuntimeError: dictionary changed size during iteration
Both failure modes render intersection_update completely non-functional.
Steps to Reproduce
Run the following script:
from openage.util.ordered_set import OrderedSet
s1 = OrderedSet([1, 2, 3])
s2 = OrderedSet([2, 3, 4])
s1.intersection_update(s2) # Raises AttributeError
d = {2: 0, 3: 1, 4: 2}
s1.intersection_update(d) # Raises RuntimeError
Verified in unit tests test_bug4_ordered_set_intersection_update_attribute_error and test_bug4_ordered_set_intersection_update_runtime_error in test_openage_bugs.py.
Expected Behavior
intersection_update should accept any iterable (including OrderedSet, set, list, or dict), compute the intersection, and safely update the set without modifying the dictionary during active iteration.
Suggested Fix
--- a/openage/util/ordered_set.py
+++ b/openage/util/ordered_set.py
@@ -86,9 +86,13 @@ class OrderedSet(Generic[OrderedSetItem]):
"""
- keys_self = set(self.ordered_set.keys())
- keys_other = set(other.keys())
- intersection = keys_self & keys_other
+ if isinstance(other, OrderedSet):
+ other_set = set(other.ordered_set.keys())
+ elif isinstance(other, dict):
+ other_set = set(other.keys())
+ else:
+ other_set = set(other)
- for elem in self:
- if elem not in intersection:
+ for elem in list(self.ordered_set.keys()):
+ if elem not in other_set:
self.discard(elem)