← 输入框|github.com|刷新
Skip to content

Fix hash contract: equal Versions must hash equal (#515) - #516

Merged
tomschr merged 6 commits into
python-semver:masterfrom
SonicHedghog:fix-hash-equal-versions
Nov 18, 2026
Merged

tomschr merged 6 commits into
python-semver:masterfrom
SonicHedghog:fix-hash-equal-versions

Conversation

@SonicHedghog

Copy link
Copy Markdown
Contributor

Summary

Version.__hash__ hashed to_tuple()[:4] — the raw prerelease string — while compare()/_nat_cmp normalizes numeric identifiers before comparing. A zero-padded prerelease ("007") compares equal to its normalized form ("7") but hashed differently, so equal Version objects behaved as distinct keys in set/dict — a violation of Python's __eq__/__hash__ contract, live since 3.0.3 (commit 0f30183 fixed the _nat_cmp tiebreak without updating __hash__).

Fix

  • Hoisted the prerelease-identifier normalization out of _nat_cmp into a shared _prerelease_key static method — comparison and hashing now consume the same normalization and cannot drift again.
  • __hash__ builds its key from the normalized identifier keys; a falsy (None/"") prerelease maps to a canonical empty key so Version(1,2,3) and Version(1,2,3,"") hash identically (they compare equal).
  • Build metadata stays excluded, matching SemVer §10 precedence rules.

Non-breaking: changes no public behavior except restoring the __eq__/__hash__ contract. Alternative rejected: validating leading zeros in __init__ would fix the reachable state but is a breaking change (tracked as a possible semver-4 item).

Test plan

  • New parametrized test test_equal_prereleases_have_equal_hashes — 4 cases: zero-padded numeric, zero-padded mid-identifier, non-ASCII digit (٧), empty-vs-absent prerelease; each asserts equality, hash equality, set dedup, and dict lookup.
  • Full suite: 531 passed, 1 skipped (pytest tests), 100% coverage on src/semver/version.py maintained.
  • ruff check on changed file adds zero new findings vs HEAD.
  • Verified manually: {Version(1,2,3,'007'), Version(1,2,3,'7')} now has length 1; {a: 'v'}.get(b) hits.

Fixes #515

Version.__hash__ hashed to_tuple()[:4], keeping the raw prerelease
string, while _nat_cmp normalizes numeric identifiers for comparison.
A zero-padded prerelease (e.g. "007") compared equal to its normalized
form ("7") but hashed differently, so equal Versions behaved as
distinct set/dict keys — a contract violation live since 3.0.3.

Hoist the prerelease normalization out of _nat_cmp into a shared
_prerelease_key helper and build the hash from the normalized key, so
comparison and hashing cannot drift again. Empty/absent prerelease
maps to a canonical key.

Adds parametrized coverage for zero-padded, multi-identifier,
non-ASCII-digit, and empty-prerelease equalities (set/dict semantics
included), plus a changelog fragment.

Fixes python-semver#515
@SonicHedghog

Copy link
Copy Markdown
Contributor Author

The two `action_required` checks are the first-time-contributor workflow gate (zero jobs ran) — they'll need a maintainer's "Approve and run." For reference: `pytest tests` passes locally on this branch (531 passed, 1 skipped, Python 3.13) and `ruff check` adds no new findings vs HEAD.

@tomschr tomschr left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thank you @SonicHedghog for your PR! Much appreciated! 👍

I guess, I found an edge case. Could you take a look? Let me know what you think. 😊

Comment thread src/semver/version.py Outdated
return (1, 0, identifier)
@staticmethod
def _prerelease_key(identifier: str) -> tuple[int, int, str]:
if not identifier.isdigit():

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think the .isdigit() is wrong here. It allows too much. For example:

>>> identifier = "²"
>>> identifier.isdigit()
True
>>> identifier.isdecimal()
False

Only regular decimals should be allowed, not superscripts like "²". That numeric which will make int("²") fail later.

Suggested change
if not identifier.isdigit():
if not identifier.isdecimal():

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Great catch — you're absolutely right, isdigit() accepts superscripts and other non-decimal digits that int() chokes on. Switched to isdecimal() in 9df3f6a.

One side effect worth flagging: this changed the behavior that #488 locked in — compare() used to raise ValueError eagerly for these identifiers, but now ² sorts lexically as an alphanumeric identifier instead. I updated test_should_preserve_eager_invalid_unicode_digit_error accordingly (now test_should_compare_superscript_digit_as_alphanumeric), but let me know if you'd rather keep the error path.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the hint. I think that's fine. 👍 If not, I hope people will come up with additional issue or PRs. 😆

Comment thread src/semver/version.py Outdated
if not identifier.isascii():
identifier = str(int(identifier))
if not identifier.isascii():
identifier = str(int(identifier))

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Use Unicode decimal-category digits and normalize each character individually. This avoids treating superscript "²" as numeric even though int("²") fails, while preserving Arabic-Indic digit equivalence and avoiding Python’s integer-string length limit.

You may need to add import unicodedata in the header:

Suggested change
identifier = str(int(identifier))
identifier = "".join(
str(unicodedata.decimal(character)) for character in identifier
)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Applied — per-character unicodedata.decimal normalization is a nice touch, handles Arabic-Indic and fullwidth digits without ever hitting int() or the integer-string length limit. Thanks!

str.isdigit() accepts superscripts like "²" for which int() fails, and
since __hash__ now reaches _prerelease_key, the crash became reachable
from hashing too. Switch to str.isdecimal() and normalize each
character via unicodedata.decimal, which also avoids Python's
integer-string length limit and removes int() from prerelease
comparison entirely.

Deliberately supersedes the eager ValueError introduced for these
identifiers in python-semver#488: a prerelease like "²" now compares lexically as an
alphanumeric identifier instead of raising. Test updated accordingly.
@SonicHedghog

Copy link
Copy Markdown
Contributor Author

Fixed in 9df3f6a — ² and friends are now treated as alphanumeric identifiers rather than numeric (or a crash). Bonus: __hash__ reaching _prerelease_key meant the superscript case would've been a brand-new crash path under this PR, so this genuinely needed catching. 😅 Suite is green locally: 532 passed, still 100% coverage on version.py.

@SonicHedghog

Copy link
Copy Markdown
Contributor Author

Heads-up on the red check: it's not the change — `tox-gh-actions` crashes at import with `ImportError: cannot import name '_PLACE_HOLDER' from 'tox.config.of_type'`. tox 4.67.14/4.67.15 shipped yesterday (~22:30 UTC), right between the green run on the previous commit and this one, and the workflow installs it unpinned. This will hit every run repo-wide until pinned (e.g. `tox<4.67.14`) or tox-gh-actions catches up. Local suite is still green on this branch (532 passed).

@tomschr

tomschr commented Nov 18, 2026

Copy link
Copy Markdown
Member

Heads-up on the red check: it's not the change — tox-gh-actions crashes at import with ImportError: cannot import name '_PLACE_HOLDER' from 'tox.config.of_type'

Thanks, great catch! 👍 I will look into it. 👀

@tomschr

tomschr commented Nov 18, 2026

Copy link
Copy Markdown
Member

Ok, I pushed commit 53e92bd, let's see if that works. 🤞

@SonicHedghog

Copy link
Copy Markdown
Contributor Author

Almost — the pin didn't reach the matrix jobs. The workflow installs tox a second time, unpinned, after sync:

@tomschr

tomschr commented Nov 18, 2026

Copy link
Copy Markdown
Member

Looks like I was able to use the pinned tox version.🎉 If you would like to have a look, let me know if that looks good.

Maybe I should better separate your issue from the infrastructure part.🤔

@SonicHedghog

Copy link
Copy Markdown
Contributor Author

Infra change looks good to me — `uv sync --locked --group gh-action` makes both jobs resolve from the lockfile, and `tox<4.67.14` in the `test` extra is what actually constrains it now. Green matrix confirms it. 🎉

@tomschr

tomschr commented Nov 18, 2026

Copy link
Copy Markdown
Member

Infra change looks good to me

Great! 🎉

The clean way would be to have a separate PR for the infra structure part. However, I'm a bit lazy today 😹 so I think we combine it in this one PR. 😉😇

Once the CI is green, I will merge it to the master branch.

Many thanks for your contribution! ❤️

@SonicHedghog

Copy link
Copy Markdown
Contributor Author

Works for me — combined is fine since it all lands together anyway. Thanks for the review and for sorting the CI bits! 🙌

@tomschr
tomschr merged commit a4b7d33 into python-semver:master Nov 18, 2026
30 of 32 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Equal Version objects can have different hashes (zero-padded prerelease)

2 participants