Repository navigation
Speed up Version hot paths and fix pickling on protocols 0-1 - #528
ceedot-rock wants to merge 19 commits into
Conversation
There was a problem hiding this comment.
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:
next_version()can return an older version.- `is_valid() bypasses subclass validation.
- Private subclass slots are lost during pickle/copy.
from_parts()bypasses subclass__new__- Caches can become stale for subclasses in
__str__and `hash - 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.
| # As recommended in the Python documentation | ||
| # https://docs.python.org/3/library/inspect.html#the-interpreter-stack | ||
| # better remove the interpreter stack: |
| 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. |
There was a problem hiding this comment.
I would use Sphinx roles:
| 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. |
| from .version import Version | ||
| from .__about__ import __version__ | ||
|
|
||
| _BUMP_METHODS = { |
There was a problem hiding this comment.
I would remove the leading underscore:
| _BUMP_METHODS = { | |
| BUMP_METHODS = { |
| # 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)) |
There was a problem hiding this comment.
| return str(_BUMP_METHODS[cast(str, args.bump)](ver)) | |
| return str(BUMP_METHODS[cast(str, args.bump)](ver)) |
| # 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 | ||
| ) |
There was a problem hiding this comment.
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| version += "-%s" % self.prerelease | ||
| if self.build: | ||
| version += "+%s" % self.build | ||
| self._str = version |
There was a problem hiding this comment.
| self._str = version | |
| if cache: | |
| self._str = version |
| return version | ||
|
|
||
| def __hash__(self) -> int: | ||
| cached = getattr(self, "_hash", None) |
There was a problem hiding this comment.
Same here:
| cached = getattr(self, "_hash", None) | |
| cache = type(self) is Version | |
| cached = getattr(self, "_hash", None) if cache else None |
| ) | ||
| return hash((self.major, self.minor, self.patch, prerelease)) | ||
| result = hash((self.major, self.minor, self.patch, prerelease)) | ||
| self._hash = result |
There was a problem hiding this comment.
| self._hash = result | |
| if cache: | |
| self._hash = result |
| and len(prerelease or "") <= 255 | ||
| and len(build or "") <= 255 |
There was a problem hiding this comment.
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:
| and len(prerelease or "") <= 255 | |
| and len(build or "") <= 255 | |
| and len(prerelease or "") + len(build or "") <= 220 |
| 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 |
There was a problem hiding this comment.
This if clause is redundant. The combined <= 220 condition implies neither individual metadata string can exceed 220, so the separate <= 255 checks are unnecessary:
| 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 |
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:
Versioncould 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.deepcopyof an exactVersionreturnself, reflecting immutability; subclasses copy their full state.Performance (micro-benchmark, best of 5, µs/op; ratios are the stable part):
Version(1,2,3)Version.parse("10.20.30")</==hash()/str()bump_patch()is_valid()Key changes: fast-path construction for plain
int/strinputs (full validation unchanged underneath, includingMAX_LENGTHand negative checks, error precedence preserved); positional/indexed regex groups inparse(); slot-direct comparison with lazy prerelease keys; cached comparator type tuples; lazy__hash__/__str__caches (NAMESdecoupled from__slots__); regex-onlyis_valid; validated internal constructor forbump_*/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-freenext_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.__init__invalidates the caches.Tests
pytest, tests + doctests): 658 passed, 1 skipped, 100% branch coverage ofsrc/semvermaintained.tests/test_perf_contracts.py(contract tests per change: error types/messages, boundary lengths, subclass hooks, pickle legacy state) andtests/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.