Project

General

Profile

Actions

Bug #22595

open

ObjectSpace::WeakMap#each can yield the same pair twice if compaction happens during iteration

Bug #22595: ObjectSpace::WeakMap#each can yield the same pair twice if compaction happens during iteration

Added by jhawthorn (John Hawthorn) about 8 hours ago.

Status:
Open
Assignee:
-
Target version:
-
ruby -v:
ruby 4.1.0dev (2026-11-16) +PRISM [x86_64-linux]
[ruby-core:127563]

Description

Reproduces on 4.0.9 and master:

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.

No data to display

Actions

Also available in: PDF Atom