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

Speed up Version hot paths and fix pickling on protocols 0-1 - #528

Open
ceedot-rock wants to merge 19 commits into
python-semver:masterfrom
ceedot-rock:upstream-perf
Open

ceedot-rock wants to merge 19 commits into
python-semver:masterfrom
ceedot-rock:upstream-perf

Conversation

@ceedot-rock

Copy link
Copy Markdown

Summary

A series of behavior-preserving optimizations to the pure-Python hot paths, plus one bug fix. Each commit is self-contained and was verified against the full test suite and a micro-benchmark before landing.

Bug fix: Version could not be pickled with pickle protocols 0–1 (__slots__ class without __getstate__). It now defines __getstate__/__setstate__ in the legacy state shape, so older pickles keep loading. copy.copy/copy.deepcopy of an exact Version return self, reflecting immutability; subclasses copy their full state.

Performance (micro-benchmark, best of 5, µs/op; ratios are the stable part):

case before after speedup
Version(1,2,3) 2.25 0.34 6.6×
Version.parse("10.20.30") 3.24 1.15 2.8×
< / == 0.73 / 0.89 0.26 / 0.26 ~3×
hash() / str() 0.75 / 0.51 0.09 / 0.06 ~8×
bump_patch() 2.50 0.31 8.1×
is_valid() 3.83 0.66 5.8×
sort 50 versions 175 52 3.3×

Key changes: fast-path construction for plain int/str inputs (full validation unchanged underneath, including MAX_LENGTH and negative checks, error precedence preserved); positional/indexed regex groups in parse(); slot-direct comparison with lazy prerelease keys; cached comparator type tuples; lazy __hash__/__str__ caches (NAMES decoupled from __slots__); regex-only is_valid; validated internal constructor for bump_*/finalize_version/parse (falls back to full __init__ for custom-__init__ subclasses and near-limit sizes, so boundary errors like bumping a 255-char version still raise); regex-free next_version("prerelease"); precomputed deprecation warning text; hoisted CLI dispatch.

Compatibility notes:

  • parse() now calls the constructor positionally; subclass __init__ must keep the documented (major, minor, patch, prerelease, build) order.
  • Cached hash/string assume the documented immutability; re-running __init__ invalidates the caches.
  • Two extra slots per instance (caches) trade a little memory for the hash/str speedups.

Tests

  • Full suite (pytest, tests + doctests): 658 passed, 1 skipped, 100% branch coverage of src/semver maintained.
  • New tests/test_perf_contracts.py (contract tests per change: error types/messages, boundary lengths, subclass hooks, pickle legacy state) and tests/test_invariants.py (total ordering, hash/equality agreement, bump monotonicity, roundtrips over a seeded pool).
  • mypy src: unchanged (1 pre-existing missing-stub error for the optional Rust backend). ruff check: no new findings.

Happy to split this into smaller PRs (e.g. pickle fix separately) if that is easier to review.

@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 @ceedot-rock for the contribution! 👍 The speedups are impressive! 🤩

I like the pickle idea, didn't think of that to add it.😆

I have a few suggestions/findings that may affect compatibility:

  1. next_version() can return an older version.
  2. `is_valid() bypasses subclass validation.
  3. Private subclass slots are lost during pickle/copy.
  4. from_parts() bypasses subclass __new__
  5. Caches can become stale for subclasses in __str__ and `hash
  6. Constructor fast path has redundant nested checks

See the details below. I hope they makes sense. Haven't tested them if they affect the performance. Let me know what you think.

Comment thread src/semver/_deprecated.py
Comment on lines -77 to -79
# As recommended in the Python documentation
# https://docs.python.org/3/library/inspect.html#the-interpreter-stack
# better remove the interpreter stack:

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.

Please keep this comment.

Comment on lines +1 to +6
Speed up the pure-Python ``Version`` hot paths (construction, parsing,
comparison, hashing, ``is_valid``, ``match``, and the ``bump_*`` methods)
and make ``Version`` picklable with all pickle protocols. Pickles created
by earlier versions continue to load. ``copy.copy`` and
``copy.deepcopy`` of an exact ``Version`` now return the instance itself,
reflecting its immutability.

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 would use Sphinx roles:

Suggested change
Speed up the pure-Python ``Version`` hot paths (construction, parsing,
comparison, hashing, ``is_valid``, ``match``, and the ``bump_*`` methods)
and make ``Version`` picklable with all pickle protocols. Pickles created
by earlier versions continue to load. ``copy.copy`` and
``copy.deepcopy`` of an exact ``Version`` now return the instance itself,
reflecting its immutability.
Speed up the pure-Python :class:`~semver.version.Version` hot paths
(construction, parsing, comparison, hashing, :meth:`~semver.version.Version.is_valid`,
:meth:`~semver.version.Version.match`, and the ``bump_*`` methods) and make
:class:`~semver.version.Version` picklable with all :mod:`pickle` protocols.
Pickles created by earlier versions continue to load. :func:`copy.copy` and
:func:`copy.deepcopy` of an exact :class:`~semver.version.Version` now return
the instance itself, reflecting its immutability.

Comment thread src/semver/cli.py
from .version import Version
from .__about__ import __version__

_BUMP_METHODS = {

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 would remove the leading underscore:

Suggested change
_BUMP_METHODS = {
BUMP_METHODS = {

Comment thread src/semver/cli.py
# get the respective method and call it
func = getattr(ver, maptable[cast(str, args.bump)])
return str(func())
return str(_BUMP_METHODS[cast(str, args.bump)](ver))

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.

Suggested change
return str(_BUMP_METHODS[cast(str, args.bump)](ver))
return str(BUMP_METHODS[cast(str, args.bump)](ver))

Comment thread src/semver/version.py
Comment on lines +778 to +789
# Greater iff the new first identifier sorts after the
# old one (digit handling identical to _prerelease_key).
old_first = prerelease.split(".", 1)[0]
cand_first = prerelease_token.split(".", 1)[0]
first_cmp = _cmp(
cls._prerelease_key(cand_first),
cls._prerelease_key(old_first),
)
if candidate > version:
return candidate
if first_cmp > 0 or cand_first == old_first:
return version.replace(
prerelease=new_prerelease, build=None
)

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.

This part can return an older version for dotted tokens. It ignores subsequent prerelease identifiert. A 1.2.3-alpha.gamma with token alpha.beta produces 1.2.3-alpha.beta.1, which is less than the input.

Test:

>>> v = Version.parse("1.2.3-alpha.gamma")
>>> v.next_version("prerelease", "alpha.beta") > v
False # <= wrong

Comment thread src/semver/version.py
version += "-%s" % self.prerelease
if self.build:
version += "+%s" % self.build
self._str = version

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.

Suggested change
self._str = version
if cache:
self._str = version

Comment thread src/semver/version.py
return version

def __hash__(self) -> int:
cached = getattr(self, "_hash", None)

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.

Same here:

Suggested change
cached = getattr(self, "_hash", None)
cache = type(self) is Version
cached = getattr(self, "_hash", None) if cache else None

Comment thread src/semver/version.py
)
return hash((self.major, self.minor, self.patch, prerelease))
result = hash((self.major, self.minor, self.patch, prerelease))
self._hash = result

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.

Suggested change
self._hash = result
if cache:
self._hash = result

Comment thread src/semver/version.py
Comment on lines +215 to +216
and len(prerelease or "") <= 255
and len(build or "") <= 255

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.

The constructor fast-path checks are redundant. The three upper-bound checks and the combined-length check are repeated in the inner if. The outer condition can include:

Suggested change
and len(prerelease or "") <= 255
and len(build or "") <= 255
and len(prerelease or "") + len(build or "") <= 220

Comment thread src/semver/version.py
Comment on lines +233 to +246
if (
major < 1_000_000_000
and minor < 1_000_000_000
and patch < 1_000_000_000
and len(prerelease or "") + len(build or "") <= 220
):
self._major = major
self._minor = minor
self._patch = patch
self._prerelease = prerelease
self._build = build
self._hash = None
self._str = None
return

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.

This if clause is redundant. The combined <= 220 condition implies neither individual metadata string can exceed 220, so the separate <= 255 checks are unnecessary:

Suggested change
if (
major < 1_000_000_000
and minor < 1_000_000_000
and patch < 1_000_000_000
and len(prerelease or "") + len(build or "") <= 220
):
self._major = major
self._minor = minor
self._patch = patch
self._prerelease = prerelease
self._build = build
self._hash = None
self._str = None
return
self._major = major
self._minor = minor
self._patch = patch
self._prerelease = prerelease
self._build = build
self._hash = None
self._str = None
return

This branch has not been deployed

No deployments
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.

2 participants