WeakKeyDictionary results in large amount of contention when used with free threading

A common use of WeakKeyDictionary is to attach some private metadata to a potentially immutable object.

a WeakKeyDictionary is currently used in Trio to mark code objects as “keyboard interrupt protected”, in anyio a WeakKeyDictionary is used to make a task to its nearest parent CancelScope

I’ve recently been informed by @kumaraditya303 that WeakKeyDictionary is no longer suitable for this usecase on free-threading due to lock contention

I was wondering if a C acceleration version of WeakKeyDictionary, SimpleWeakKeyDictionary could be created that does not need a lock, by preventing iteration and using identity key semantics

Another approach would be an Ephemeron class, or an api like JavaScript Symbols:

my_metadata = symbols.Symbol("my_metadata")
...
setbysymbol(task, my_metadata, self.cancel_scope)
...
cancel_scope = getbysymbol(task, my_metadata)