Skip to content

gh-153852: Fix data race in hash cal for Decimal - #154519

Closed
weixlu wants to merge 1 commit into
python:mainfrom
weixlu:hash
Closed

gh-153852: Fix data race in hash cal for Decimal#154519
weixlu wants to merge 1 commit into
python:mainfrom
weixlu:hash

Conversation

@weixlu

@weixluweixlu commented Jul 23, 2026

Copy link
Copy Markdown
Contributor

As reported in TSAN0005 in #153852, there is a harmless data race in decimal's hash calculation. On a no-GIL build, two threads hashing the same decimal object for the first time concurrently produce a data race on self->hash. Fortunately, this is harmless because it is value-benign—both threads compute the exact same hash value. However, it is indeed an unsynchronized read-then-write, and ThreadSanitizer will report this issue.

A similar thing occurs in Unicode's hash calculation, which also uses a caching mechanism similar to decimal. In PR #134892, @colesbury mentioned:

Hash can be computed and assigned concurrently so to avoid a data race in free-threaded build:
#ifdef Py_GIL_DISABLED
return _Py_atomic_load_ssize_relaxed(&_PyASCIIObject_CAST(op)->hash);

Perhaps decimal could adopt the same approach here. But of course, since this potential data race is value-benign, I'm totally OK if we just leave this as is.

Reproduce:

  • ./configure --disable-gil --with-thread-sanitizer
  • make -j
  • TSAN_OPTIONS="halt_on_error=1 symbolize=1 history_size=4" ./python repro_dec_hash.py
  • repro_dec_hash.py

@ByteFlowing1337

Copy link
Copy Markdown
Contributor

There is already a PR to fix it: #154045.

@weixlu

Copy link
Copy Markdown
ContributorAuthor

There is already a PR to fix it: #154045.

Oh sorry, I haven't noticed this. Thanks for pointing out!

@weixluweixlu closed this Jul 23, 2026
@weixlu
weixlu deleted the hash branch July 23, 2026 03:50
Sign up for freeto join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants

@weixlu@ByteFlowing1337