From: "jhawthorn (John Hawthorn) via ruby-core" Date: 2026-11-17T19:26:37+00:00 Subject: [ruby-core:127563] [Ruby Bug#22595] ObjectSpace::WeakMap#each can yield the same pair twice if compaction happens during iteration Issue #22595 has been reported by jhawthorn (John Hawthorn). ---------------------------------------- Bug #22595: ObjectSpace::WeakMap#each can yield the same pair twice if compaction happens during iteration https://bugs.ruby-lang.org/issues/22595 * Author: jhawthorn (John Hawthorn) * Status: Open * ruby -v: ruby 4.1.0dev (2026-11-16) +PRISM [x86_64-linux] * Backport: 3.3: UNKNOWN, 3.4: UNKNOWN, 4.0: UNKNOWN ---------------------------------------- Reproduces on 4.0.9 and master: ```ruby map = ObjectSpace::WeakMap.new key = Object.new map[key] = 1 100.times { |i| map[i] = i } count = 0 map.each do GC.verify_compaction_references(expand_heap: true, toward: :empty) if count == 10 count += 1 end p [map.size, count] # => [101, 102] ``` WeakMap hashes keys by address, so when compaction moves a key `wmap_compact` deletes it and reinserts it at the end of the table, where the `st_foreach` in `#each` reaches it a second time. If that reinsertion rebuilds the table, `#each` stops early instead. The block deleting the current key and then inserting enough to rebuild the table makes it stop early or start over from the first entry. This affects `each`, `each_key`, `each_value` and `inspect`. -- https://bugs.ruby-lang.org/ ______________________________________________ ruby-core mailing list -- ruby-core@ml.ruby-lang.org To unsubscribe send an email to ruby-core-leave@ml.ruby-lang.org ruby-core info -- https://ml.ruby-lang.org/mailman3/lists/ruby-core.ml.ruby-lang.org/