From 26a696924ee9eae9d0a9dc1db6ff6e8e18d8859d Mon Sep 17 00:00:00 2001 From: Jonathan Yoder Date: Tue, 4 Aug 2026 18:46:01 -0400 Subject: [PATCH] fix(version): normalize all-digit local segments as integers MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit PEP 440: "If a segment consists entirely of ASCII digits then that section should be considered an integer", so its integer-normalization rule ("an integer version of 00 would normalize to 0") reaches such a segment. We left it verbatim: `1.0+007` rendered as `1.0+007` where pypa/packaging renders `1.0+7`. ⚠️ THE CARVE-OUT IS EASY TO READ BACKWARDS, and reading it backwards is how this was missed. PEP 440's exemption is scoped to integers inside an ALPHANUMERIC local segment -- "such as 1.0+foo0100 which is already in its normalized form." It does NOT exempt an all-digit segment. So `foo0100` stays exactly as it is while `007` becomes `7`, and the reference implementation does precisely that: `part.lower() if not part.isdigit() else int(part)`. ORDERING WAS NEVER WRONG, which is why nothing caught this. cmpkey already compares all-digit segments numerically, so `1.0+007` and `1.0+7` compared equal before and after -- verified, and asserted in the test so nobody "simplifies" the normalization away on the grounds that comparison covers it. The defect is the rendered STRING, and the one place that is load-bearing is `===`: PEP 440 defines arbitrary equality as string equality on the normalized form, so `===1.0+7` failed to match `1.0+007` while upstream matched it. The test drives that through NewSpecifiers rather than only comparing String() output, because the specifier path is where a consumer would actually feel it. HOW IT WAS FOUND, because the provenance is the interesting part. A differential run compared this package against pypa/packaging 26.2 over every distinct version string in a production PyPI snapshot: 634,187 strings, with identical accept/reject on all of them, identical normalized rendering on all 634,150 accepted, and identical total order across all 680,711 packages. That corpus could not possibly have found this bug. PEP 440 forbids the Python Package Index from accepting local version identifiers at all, so the real corpus contained ZERO of them -- and local labels are exactly what 0.2.0 changed. The finding came from the synthetic supplement that was added precisely because the real data could not exercise the new code. Worth recording as a method: a clean differential over a large real corpus says nothing about the shapes that corpus cannot contain, so check coverage of the shapes you changed rather than the size of the dataset. Also from that run, and NOT changed here: - `1.0.poſt1` (U+017F) parses here and is rejected upstream, because Go's `(?i)` case-folds Unicode while PEP 440 scopes case-insensitivity to ascii letters. Over-acceptance, unreachable from PyPI, left for a follow-up. - We reject `1.0\xa0`, `1.0\x85` and `1.0 `, which upstream accepts. Here WE are right: PEP 440 enumerates the strippable whitespace exhaustively as space, \t, \n, \r, \f, \v, which is what this package implements. Python's Unicode `\s` is an upstream deviation, so this is deliberately not "fixed". CHANGELOG entry goes in the unreleased 0.2.0 Breaking section, beside the related local-label entry, since it changes rendered output and 0.2.0 is not yet tagged. Both new tests verified to fail individually with only this fix reverted, and the Compare assertion verified to pass either way -- which is the evidence that the defect really is rendering-only rather than an ordering bug in disguise. Co-Authored-By: Claude Opus 5 --- CHANGELOG.md | 9 ++++ version/local_normalization_test.go | 80 +++++++++++++++++++++++++++++ version/version.go | 50 +++++++++++++++++- 3 files changed, 137 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 95f2fea..af1d1a5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -44,6 +44,15 @@ rather than `0.1.3`. *above* `1.0+ubuntu-10`. It now sorts below, matching upstream. Consumers that persist or compare rendered versions, or that rely on the previous sort order of dash- or underscore-separated local labels, will see a difference. +- A local version segment consisting entirely of ASCII digits normalizes as an integer, + so `1.0+007` renders as `1.0+7` and `1.0+ubuntu-007` as `1.0+ubuntu.7`. PEP 440 says + such a segment "should be considered an integer", and scopes its + no-normalization carve-out to integers inside an *alphanumeric* segment — so + `1.0+foo0100` is still left exactly as it is. **Ordering is unaffected**: those + segments were already compared numerically, so `1.0+007` and `1.0+7` compared equal + before and after. What changes is the rendered string, and therefore arbitrary + equality: `===1.0+7` now matches `1.0+007`, as upstream does, where it previously + did not. ### Added diff --git a/version/local_normalization_test.go b/version/local_normalization_test.go index 126aec8..468fc9a 100644 --- a/version/local_normalization_test.go +++ b/version/local_normalization_test.go @@ -115,3 +115,83 @@ func TestSurroundingWhitespaceIncludesVerticalTab(t *testing.T) { } } } + +// TestAllDigitLocalSegmentsNormalizeAsIntegers covers a third divergence, found +// by a differential run over 634,187 distinct real PyPI version strings — which +// is worth stating plainly, because that corpus could not possibly have found +// it: PEP 440 forbids PyPI from accepting local versions at all, so the corpus +// contained ZERO of them and this came out of the synthetic supplement. +// +// PEP 440: "If a segment consists entirely of ASCII digits then that section +// should be considered an integer", and its integer-normalization rule ("an +// integer version of 00 would normalize to 0") therefore reaches such a +// segment. The rule's carve-out is scoped to integers inside an ALPHANUMERIC +// segment, "such as 1.0+foo0100 which is already in its normalized form". +// +// Expected values below are the measured output of str(packaging.version.Version(s)), +// not a reading of the spec — the spec settles which implementation is right, the +// reference settles what the answer looks like. +func TestAllDigitLocalSegmentsNormalizeAsIntegers(t *testing.T) { + for _, tc := range []struct{ in, want string }{ + {"1.0+007", "1.0+7"}, + {"1.0+7", "1.0+7"}, + {"1.0+00", "1.0+0"}, // All zeros is the integer 0, not the empty string. + {"1.0+0", "1.0+0"}, + {"1.0+ubuntu.007", "1.0+ubuntu.7"}, + {"1.0+ubuntu-007", "1.0+ubuntu.7"}, // Separator and integer normalization compose. + {"1.0+007.ubuntu", "1.0+7.ubuntu"}, + {"1.0+foo0100", "1.0+foo0100"}, // Alphanumeric: the carve-out, left alone. + {"1.0+0foo", "1.0+0foo"}, // Also alphanumeric, despite the leading zero. + {"1.0+09000", "1.0+9000"}, + } { + v, err := Parse(tc.in) + if err != nil { + t.Errorf("Parse(%q): unexpected error %v", tc.in, err) + continue + } + if got := v.String(); got != tc.want { + t.Errorf("Parse(%q).String() = %q, want %q", tc.in, got, tc.want) + } + } +} + +// TestAllDigitLocalNormalizationIsObservableOnlyViaArbitraryEquality pins WHY +// the normalization above matters, so a future reader does not conclude it is +// cosmetic and drop it. +// +// Ordering was already correct without it, because cmpkey compares all-digit +// segments numerically either way — so no comparison test could have caught the +// bug. PEP 440 defines "===" as string equality on the normalized form, which is +// the one place the rendering is load-bearing. +func TestAllDigitLocalNormalizationIsObservableOnlyViaArbitraryEquality(t *testing.T) { + padded, err := Parse("1.0+007") + if err != nil { + t.Fatalf("Parse: %v", err) + } + bare, err := Parse("1.0+7") + if err != nil { + t.Fatalf("Parse: %v", err) + } + + // The half that was always right: they compare equal. + if got := padded.Compare(bare); got != 0 { + t.Errorf("Compare(1.0+007, 1.0+7) = %d, want 0 — all-digit segments compare "+ + "numerically, which was never the defect", got) + } + + // The half that was wrong: "===" is string equality, so the strings must match. + if padded.String() != bare.String() { + t.Errorf("String() forms differ (%q vs %q), so \"===1.0+7\" would fail to match "+ + "\"1.0+007\" while the reference implementation matches it", + padded.String(), bare.String()) + } + + spec, err := NewSpecifiers("===1.0+7") + if err != nil { + t.Fatalf("NewSpecifiers: %v", err) + } + if !spec.Check(padded) { + t.Error("\"===1.0+7\" must match 1.0+007: PEP 440 defines === as string equality " + + "on the normalized form, and 007 normalizes to 7") + } +} diff --git a/version/version.go b/version/version.go index f5ae28e..db77564 100644 --- a/version/version.go +++ b/version/version.go @@ -102,7 +102,8 @@ func init() { var localVersionSeparators = regexp.MustCompile(`[._-]`) // normalizeLocal normalizes a local version label: PEP 440 requires "-" and -// "_" separators to be rewritten as ".", and the label to be lowercased. +// "_" separators to be rewritten as ".", the label to be lowercased, and any +// segment consisting entirely of ASCII digits to be normalized as an integer. // // Normalizing the separator is not cosmetic. cmpkey splits the label on "." // to compare it segment by segment, with numeric segments ordering above @@ -110,8 +111,53 @@ var localVersionSeparators = regexp.MustCompile(`[._-]`) // alphabetic segment and compared lexicographically. That makes // "1.0+ubuntu-10" sort BELOW "1.0+ubuntu-2" -- a silent wrong answer of the // same kind as rstudio/package-manager#19369. +// +// # Why all-digit segments have their leading zeros stripped +// +// PEP 440: "If a segment consists entirely of ASCII digits then that section +// should be considered an integer" — and its integer-normalization rule ("an +// integer version of 00 would normalize to 0") therefore reaches it. The rule's +// one carve-out is scoped to integers inside an ALPHANUMERIC local segment, +// "such as 1.0+foo0100 which is already in its normalized form", so "foo0100" +// is left exactly as it is while "007" becomes "7". +// +// That asymmetry is easy to get backwards, so note what it is NOT about: +// ordering was already correct without this, because cmpkey compares all-digit +// segments numerically either way. What it changes is the normalized STRING — +// and PEP 440 defines the "===" arbitrary-equality operator as string equality +// on that form, so without this "===1.0+7" fails to match "1.0+007" while the +// reference implementation matches it. func normalizeLocal(local string) string { - return localVersionSeparators.ReplaceAllString(strings.ToLower(local), ".") + lowered := localVersionSeparators.ReplaceAllString(strings.ToLower(local), ".") + + segments := strings.Split(lowered, ".") + for i, seg := range segments { + if isASCIIDigits(seg) { + segments[i] = strings.TrimLeft(seg, "0") + if segments[i] == "" { + // The segment was all zeros, which is the integer 0. + segments[i] = "0" + } + } + } + return strings.Join(segments, ".") +} + +// isASCIIDigits reports whether s is non-empty and every byte is an ASCII digit. +// +// Deliberately not unicode.IsDigit: PEP 440 says "entirely of ASCII digits", and +// admitting other Unicode digit forms here would accept labels the grammar +// rejects and hand strconv-shaped input to a numeric comparison. +func isASCIIDigits(s string) bool { + if s == "" { + return false + } + for i := 0; i < len(s); i++ { + if s[i] < '0' || s[i] > '9' { + return false + } + } + return true } // MustParse is like Parse but panics if the version cannot be parsed.