diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 28ce2de..84e5023 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -22,6 +22,12 @@ jobs: run: go vet ./... - name: Test run: go test ./... + - name: Test (race) + # Not redundant with the step above: TestCompareSharedVersionCopiesRace + # guards the "a parsed Version is safe to share across goroutines" + # guarantee and only fails under the race detector. Without this step a + # revert of padParts back to the in-place Parts.Padding would pass CI. + run: go test -race ./... - name: Format check run: | unformatted=$(gofmt -l .) diff --git a/CHANGELOG.md b/CHANGELOG.md index de2b80c..1fc3ec7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,62 @@ mistaken for a safe patch upgrade. ## [Unreleased] +### Notes + +- `version`: `Compare` (and everything built on it: `Equal`, `LessThan`, + `SortedVersions`, specifier evaluation) is dramatically faster for typical + versions. A fixed-size integer comparison key is computed once at `Parse` + time; when both versions carry one, comparison is a handful of integer + compares with zero allocations (~15 ns vs ~2.3–2.9 µs and 25–28 allocations + per call before). Versions that do not fit the packed layout — nonzero + epoch, a local label, more than 6 release segments after trailing-zero + stripping, a release segment ≥ 2^32, or an unusually large pre/post/dev + number — fall back to the general path, whose ordering is unchanged. + Against the production PyPI index (7,666,849 version occurrences), 97.26% + of versions pack. + + Packing was chosen over the two cheaper remedies after measuring all + three independently on the same benchmark: removing the + `reflect.DeepEqual` pre-check inside go-version's `Parts.Compare` is + worth 1.39–2.05x warm on its own, removing this package's + `String() == String()` fast path 1.18–1.51x, and both together + 1.70–3.45x — while the packed key alone reaches 2.1–5.2x and, measured + combined with the `DeepEqual` removal, gains nothing further, because + packable pairs never reach `Parts.Compare` at all. The `DeepEqual` + removal therefore stays out of this module (it belongs to + rstudio/go-version); the fast-path removal ships here (next entry). + + One cost is scoped to unpackable versions (in practice: + local-labeled ones, which PyPI itself rejects on upload but private + indexes may carry): comparing an EQUAL pair of them is somewhat slower + than before, because the general path no longer short-circuits equality + by rendering both sides to strings (see the next entry) and now pads + release segments into a fresh slice (see Fixed below). Measured end to end on go-pyresolver's resolver + benchmark: 2.1–5.2x faster warm resolutions, 3.1–11.8x cold. + + Ordering is pinned to the reference implementation in CI: fixtures ranked + by pypa/packaging 26.2 — a 338,688-version generated grid crossing every + packed-field limit, plus 10,064 unique versions sampled from the + production PyPI index — must agree with `Compare` exactly, on top of the + existing PEP 440 conformance tables. + +- `version`: `Compare` no longer renders both versions to strings as an + equality fast path. With the packed key in place that check could only + serve pairs where at least one side is unpackable, and the key comparison + answers those without the two allocations. Measured alone it was worth + 1.18–1.51x warm on the resolver benchmark; with the packed key it is + subsumed. + +### Fixed + +- `version`: comparing by-value copies of one `Version` from two goroutines + was a data race. go-version's `Parts.Normalize` leaves spare capacity on + the comparison key's release slice and `Parts.Padding` appended into it in + place, so copies shared — and wrote to — one backing array. `Compare` now + pads into a fresh slice, making it read-only on both receivers: a parsed + `Version` is now safe to share across goroutines. (The underlying + `rstudio/go-version` behaviour is unchanged; this fix sidesteps it.) + ## [0.5.0] - 2026-08-10 ### Fixed diff --git a/NOTICE b/NOTICE index 24cf5f5..18574fa 100644 --- a/NOTICE +++ b/NOTICE @@ -50,6 +50,13 @@ tags/testdata/gen_goldens.py, which drives packaging.tags directly. They are generated output rather than ported source, but the ordering they record is pypa/packaging's. +The version/ package's frozen conformance fixtures +(version/testdata/*.ranked.gz) record the total order pypa/packaging 26.2 +assigns to version strings, produced by sorting with packaging.version.Version +directly (the generation recipe is in the fixture test's doc comment). They +are generated output rather than ported source, but the ordering they record +is pypa/packaging's. + The tags/ package's embedded data/distro_baselines.json records the libc version well-known Linux distribution releases ship. Those version numbers originate in the distributions' own package repositories and were read through Repology's diff --git a/version/packed.go b/version/packed.go new file mode 100644 index 0000000..9f93603 --- /dev/null +++ b/version/packed.go @@ -0,0 +1,273 @@ +// SPDX-License-Identifier: Apache-2.0 OR MIT + +package version + +import ( + "math/big" + + "github.com/rstudio/go-version/pkg/part" +) + +// packedKey is a fixed-size encoding of a Version's PEP 440 comparison key, +// computed once at Parse time. For the versions it can represent -- the +// overwhelming majority of real PyPI versions, see below -- comparing two +// packedKeys with plain integer comparisons gives exactly the same answer as +// the general cmpkey path, without allocating, rendering strings, dispatching +// through Part interfaces, or touching math/big. +// +// A version is packable when ALL of the following hold: +// +// - epoch == 0 +// - no local version label +// - at most 6 release segments after trailing zeros are stripped +// - every release segment < 2^32 +// - pre-release number < 2^20 +// - post-release number < 2^14 +// - dev-release number < 2^25 (covers YYYYMMDD nightly datestamps) +// +// Against the production PyPI index (7,666,849 version occurrences across +// 932,861 packages) these bounds were chosen from the measured distribution: +// no version in the index carries a local label, 99.97% have <= 6 release +// segments, and the wide dev field exists because datestamped dev releases +// (1.2.3.dev20240101) are the single most common large suffix number. +// +// # Layout +// +// The key is four uint64 words, compared lexicographically (w0, then w1, w2, +// w3). PEP 440's cmpkey for a packable version is the tuple +// +// (epoch=0, release, pre, post, dev, local=-Inf) +// +// so only (release, pre, post, dev) vary, and they are laid out in exactly +// that order from the most significant bit down: +// +// w0: release[0] (32 bits) | release[1] (32 bits) +// w1: release[2] (32 bits) | release[3] (32 bits) +// w2: release[4] (32 bits) | release[5] (32 bits) +// w3: preClass (3) | preN (20) | postFlag (1) | postN (14) | devAbsent (1) | devN (25) +// +// Absent trailing release segments are stored as zero, which is sound because +// cmpkey itself strips trailing zeros: two stripped tuples compare identically +// to their zero-padded fixed-width forms. +// +// The suffix word w3 encodes the pre/post/dev tuple positions: +// +// - preClass: 0 = -Infinity (the dev-only case: no pre, no post, dev set), +// 1 = "a", 2 = "b", 3 = "rc", 4 = +Infinity (no pre-release otherwise). +// This mirrors cmpkey's substitution rules and the lexicographic order of +// the normalized letters ("a" < "b" < "rc"). +// - postFlag: 0 = no post-release (-Infinity), 1 = post-release present. +// - devAbsent: 0 = dev-release present, 1 = absent (+Infinity); a dev +// release sorts BELOW the same version without one. +// +// Each numeric field is 0 when its segment is absent, matching PEP 440's +// "1.0a" == "1.0a0". +type packedKey struct { + w0, w1, w2, w3 uint64 +} + +// Bit widths for every w3 field, and shifts DERIVED from them so that a +// width change cannot silently desynchronize the layout. The compile-time +// guards below pin the widths to exactly 64 bits: widening any field without +// shrinking another stops the build instead of quietly shifting preClass off +// the top of the word (4<<62 == 0 for a uint64, which would collapse "no +// pre-release" into the dev-only -Infinity class). +const ( + packedSegBits = 32 + packedPreClassBits = 3 + packedPreNBits = 20 + packedPostFlagBits = 1 + packedPostBits = 14 + packedDevFlagBits = 1 + packedDevBits = 25 + + // w3 shifts, least significant field first. + packedDevNShift = 0 + packedDevFlagShift = packedDevNShift + packedDevBits + packedPostNShift = packedDevFlagShift + packedDevFlagBits + packedPostFlagShift = packedPostNShift + packedPostBits + packedPreNShift = packedPostFlagShift + packedPostFlagBits + packedPreClassShift = packedPreNShift + packedPreNBits + + packedSegMax = 1< o.w0) + case k.w1 != o.w1: + return boolCmp(k.w1 > o.w1) + case k.w2 != o.w2: + return boolCmp(k.w2 > o.w2) + case k.w3 != o.w3: + return boolCmp(k.w3 > o.w3) + } + return 0 +} + +func boolCmp(greater bool) int { + if greater { + return 1 + } + return -1 +} + +// smallUint extracts b as a uint64 if it fits under limit. The zero part.BigInt +// (an absent segment) extracts as 0, which is exactly the value PEP 440 gives +// an absent number ("1.0a" == "1.0a0"). +func smallUint(b part.BigInt, limit uint64) (uint64, bool) { + bi := big.Int(b) + // IsUint64 admits big negatives' absolute values? No: IsUint64 reports + // whether the value is a non-negative integer < 2^64, and the version + // grammar cannot produce negatives in the first place. + if !bi.IsUint64() { + return 0, false + } + u := bi.Uint64() + if u > limit { + return 0, false + } + return u, true +} + +// packVersion computes the packed comparison key for a parsed version, or +// ok=false when the version does not fit the packed layout and must use the +// general comparison path. +func packVersion(epoch part.BigInt, release []part.BigInt, pre, post, dev letterNumber, local string) (packedKey, bool) { + var k packedKey + + if local != "" { + return k, false + } + // The packed layout has no epoch field, so only epoch 0 may pack. This is + // deliberately a direct sign check rather than smallUint(epoch, 0): with a + // limit of 0 the value clause of that idiom is unreachable, and it would + // read as if something other than the limit were rejecting "1!". + if bi := big.Int(epoch); bi.Sign() != 0 { + return k, false + } + // Parse never produces an empty release -- the grammar requires [0-9]+ -- + // so an empty one means a zero-value Version, which must sort BELOW every + // real version (see Compare). Packing it would give it exactly version + // "0"'s key. Today no zero-value Version reaches here (Parse is the only + // constructor that packs), but the invariant belongs to the packer, not + // to whoever calls it next. + if len(release) == 0 { + return k, false + } + + // Strip trailing zero segments; cmpkey does the same, and zero-padding + // the remainder to fixed width preserves the resulting order. + n := len(release) + for n > 0 { + if v, ok := smallUint(release[n-1], packedSegMax); ok && v == 0 { + n-- + continue + } + break + } + if n > packedMaxSegments { + return k, false + } + var segs [packedMaxSegments]uint64 + for i := 0; i < n; i++ { + v, ok := smallUint(release[i], packedSegMax) + if !ok { + return k, false + } + segs[i] = v + } + k.w0 = segs[0]<\t" lines gzipped, where equal versions +// share a dense rank, produced by sorting with pypa/packaging 26.2: +// +// - pypa-26.2-grid.ranked.gz: the exact output of gridStrings() -- every +// combination of the packed fields at and across each field's +// packability limit (338,688 versions). Set equality with gridStrings() +// is asserted, so extending the grid without regenerating the fixture +// fails loudly. +// - pypa-26.2-corpus-sample.ranked.gz: 10,064 unique version strings +// sampled (every 63rd, sorted order) from the 634,187 unique versions in +// the production PyPI index of 2026-08-04. Real data rather than +// constructed data; 3 sampled strings packaging rejects are excluded. +// +// To regenerate (needs pypa/packaging >= 26.2): +// +// python3 - <<'EOF' < input.txt | gzip -9 > fixture.ranked.gz +// import sys +// from packaging.version import Version, InvalidVersion +// seen = {} +// for line in sys.stdin: +// s = line.rstrip("\n") +// if s and s not in seen: +// try: seen[s] = Version(s) +// except InvalidVersion: pass +// rank, prev = 0, None +// for s, v in sorted(seen.items(), key=lambda kv: kv[1]): +// if prev is not None and v > prev: rank += 1 +// prev = v +// print(f"{s}\t{rank}") +// EOF +// +// The checks: every fixture string must parse; every ADJACENT pair in rank +// order must compare consistently with its ranks (full coverage of the +// order, catching local misorderings anywhere); and every pair of a +// seeded-shuffle sample must too (catching long-range and transitivity- +// breaking errors). The sample is a shuffle rather than a stride so it +// cannot phase-lock onto any periodic structure in the fixture's order. +func TestPackedConformanceFixtures(t *testing.T) { + grid := readRankedFixture(t, "pypa-26.2-grid.ranked.gz") + + // The grid fixture must describe exactly the strings gridStrings() + // generates: no more (stale fixture), no fewer (unranked grid entries). + // Both directions are asserted explicitly, and duplicates rejected -- + // a count comparison alone would let a fixture with duplicates mask + // missing boundary entries. + want := map[string]bool{} + for _, s := range gridStrings() { + want[s] = true + } + seen := make(map[string]bool, len(grid)) + for _, e := range grid { + if seen[e.s] { + t.Fatalf("grid fixture entry %q is duplicated; regenerate the fixture", e.s) + } + seen[e.s] = true + if !want[e.s] { + t.Fatalf("grid fixture entry %q is not produced by gridStrings(); regenerate the fixture", e.s) + } + } + for s := range want { + if !seen[s] { + t.Fatalf("gridStrings() generates %q but the fixture does not rank it; regenerate the fixture", s) + } + } + + checkAgainstRanks(t, "grid", grid) + checkAgainstRanks(t, "corpus-sample", readRankedFixture(t, "pypa-26.2-corpus-sample.ranked.gz")) +} + +type rankedVersion struct { + s string + rank int + v Version +} + +func readRankedFixture(t *testing.T, name string) []rankedVersion { + t.Helper() + f, err := os.Open(filepath.Join("testdata", name)) + if err != nil { + t.Fatal(err) + } + defer func() { _ = f.Close() }() + gz, err := gzip.NewReader(f) + if err != nil { + t.Fatal(err) + } + defer func() { _ = gz.Close() }() + + var out []rankedVersion + sc := bufio.NewScanner(gz) + sc.Buffer(make([]byte, 1<<20), 1<<20) + for sc.Scan() { + s, rankStr, ok := strings.Cut(sc.Text(), "\t") + if !ok { + t.Fatalf("%s: malformed line %q", name, sc.Text()) + } + rank, err := strconv.Atoi(rankStr) + if err != nil { + t.Fatalf("%s: rank in %q: %v", name, sc.Text(), err) + } + v, err := Parse(s) + if err != nil { + t.Fatalf("%s: packaging accepts %q, Parse rejects it: %v", name, s, err) + } + out = append(out, rankedVersion{s, rank, v}) + } + if err := sc.Err(); err != nil { + t.Fatal(err) + } + if len(out) < 2 { + t.Fatalf("%s: fixture is empty or truncated (%d entries)", name, len(out)) + } + return out +} + +func checkAgainstRanks(t *testing.T, name string, es []rankedVersion) { + t.Helper() + sign := func(x int) int { + switch { + case x < 0: + return -1 + case x > 0: + return 1 + } + return 0 + } + + mismatches := 0 + report := func(a, b rankedVersion, got int) { + mismatches++ + if mismatches <= 20 { + t.Errorf("%s: Compare(%q, %q) = %d, packaging ranks %d vs %d", + name, a.s, b.s, got, a.rank, b.rank) + } + } + + for i := 1; i < len(es); i++ { + a, b := es[i-1], es[i] + if got := a.v.Compare(b.v); got != sign(a.rank-b.rank) { + report(a, b, got) + } + } + + idx := make([]int, len(es)) + for i := range idx { + idx[i] = i + } + rng := rand.New(rand.NewSource(1)) + rng.Shuffle(len(idx), func(i, j int) { idx[i], idx[j] = idx[j], idx[i] }) + sample := make([]rankedVersion, 0, 1200) + for _, i := range idx[:min(1200, len(idx))] { + sample = append(sample, es[i]) + } + for i := range sample { + for j := range sample { + if got := sample[i].v.Compare(sample[j].v); got != sign(sample[i].rank-sample[j].rank) { + report(sample[i], sample[j], got) + } + } + } + if mismatches > 0 { + t.Fatalf("%s: %d mismatching pairs against the pypa/packaging reference", name, mismatches) + } + t.Logf("%s: %d entries, %d adjacent + %d sampled pairs, all consistent", + name, len(es), len(es)-1, len(sample)*len(sample)) +} diff --git a/version/packed_corpus_test.go b/version/packed_corpus_test.go new file mode 100644 index 0000000..11d7bc6 --- /dev/null +++ b/version/packed_corpus_test.go @@ -0,0 +1,47 @@ +// SPDX-License-Identifier: Apache-2.0 OR MIT + +package version + +import ( + "bufio" + "os" + "testing" +) + +// TestCorpusPackedFraction reports, for a real corpus of version strings (one +// per line, duplicates meaningful), what fraction of them pack. Skipped unless +// GPP_VERSION_CORPUS points at a corpus file. +// +// Against the production PyPI RSF of 2026-08-04 (932,861 packages, 7,666,849 +// version occurrences) this reported 97.26% packable, with 0 local labels in +// the entire index and 0.0142% nonzero epochs. +func TestCorpusPackedFraction(t *testing.T) { + path := os.Getenv("GPP_VERSION_CORPUS") + if path == "" { + t.Skip("set GPP_VERSION_CORPUS to a file of version strings") + } + f, err := os.Open(path) + if err != nil { + t.Fatal(err) + } + defer func() { _ = f.Close() }() + sc := bufio.NewScanner(f) + sc.Buffer(make([]byte, 1<<20), 1<<20) + var total, parsed, packable int + for sc.Scan() { + total++ + v, err := Parse(sc.Text()) + if err != nil { + continue + } + parsed++ + if v.packable { + packable++ + } + } + if err := sc.Err(); err != nil { + t.Fatal(err) + } + t.Logf("total=%d parsed=%d packable=%d (%.4f%% of parsed)", + total, parsed, packable, 100*float64(packable)/float64(parsed)) +} diff --git a/version/packed_test.go b/version/packed_test.go new file mode 100644 index 0000000..cc6da30 --- /dev/null +++ b/version/packed_test.go @@ -0,0 +1,320 @@ +// SPDX-License-Identifier: Apache-2.0 OR MIT + +package version + +import ( + "math/rand" + + "fmt" + "github.com/rstudio/go-version/pkg/part" + "sort" + "sync" + "testing" +) + +// compareSlow forces the general (pre-packed-key) comparison path, so the +// packed path can be checked against it. +func compareSlow(a, b Version) int { + a.packable = false + b.packable = false + return a.Compare(b) +} + +// gridStrings is a structured grid covering every packed field, its limits, +// and the fallback boundary on both sides. +// +// ⚠️ This generator and the frozen fixture testdata/pypa-26.2-grid.ranked.gz +// must describe the same set of strings; TestPackedConformanceFixtures +// enforces that. If you extend the grid, regenerate the fixture (see that +// test's doc comment) with pypa/packaging 26.2 or newer. +func gridStrings() []string { + // "0!" is an explicitly written zero epoch: it must pack (and order + // identically to the same version without it). The two trailing-zero + // releases below the 7-segment one exercise the strip-then-count order in + // packVersion: more than 6 written segments that strip back into range. + epochs := []string{"", "0!", "1!"} + releases := []string{ + "0", "1", "1.0", "1.0.0.0", "1.00", "1.2", "1.2.1", "0.0.1", + "2.31.0.20240406", "2024.1", "20240101.0", "1.2.3.4.5.6", + "1.2.3.4.5.6.7", "1.2.3.4.5.6.0.0", "1.2.3.4.5.0.0", + "4294967295.1", "4294967296.1", "1.4294967295", + "1.4294967296", "99999999999999999999.0", "1.99999999999999999999", + } + pres := []string{"", "a", "a0", "a1", "b1", "rc1", "rc2", "pre1", "c3", + "a1048575", "a1048576", "rc20240101"} + posts := []string{"", ".post", ".post0", ".post1", "-1", ".post16383", + ".post16384", ".post20240101"} + devs := []string{"", ".dev", ".dev0", ".dev1", ".dev20240101", + ".dev33554431", ".dev33554432"} + locals := []string{"", "+abc", "+1", "+abc.1", "+ubuntu-2", "+007", "+abc.10", "+abc.2"} + + var out []string + for _, e := range epochs { + for _, r := range releases { + for _, p := range pres { + for _, po := range posts { + for _, d := range devs { + for _, l := range locals { + out = append(out, e+r+p+po+d+l) + } + } + } + } + } + } + return out +} + +func gridVersions(tb testing.TB) []Version { + strs := gridStrings() + out := make([]Version, 0, len(strs)) + for _, s := range strs { + v, err := Parse(s) + if err != nil { + tb.Fatalf("grid version %q failed to parse: %v", s, err) + } + out = append(out, v) + } + return out +} + +// TestPackedAgreesWithSlowPath compares pairs from the grid through both +// paths and requires exact agreement. +// +// Only a PACKABLE x PACKABLE pair actually discriminates the two encodings: +// for any pair with an unpackable side, Compare and compareSlow run the same +// code and the assertion is x == x. So the sample is drawn packable-first -- +// the packable subset carries the information -- topped up with unpackable +// versions to exercise the boundary and the mixed-pair fallback. +// +// Sampling is a seeded SHUFFLE, not a stride. The grid is a nested cross +// product, so any fixed stride whose gcd with an inner dimension's period +// exceeds 1 silently collapses that dimension: at 204,288 versions the old +// stride of 132 shared a factor of 4 with the 8-value locals dimension and +// sampled only 2 of its 8 values. A shuffle has no phase to lock onto. +func TestPackedAgreesWithSlowPath(t *testing.T) { + full := gridVersions(t) + rng := rand.New(rand.NewSource(1)) + rng.Shuffle(len(full), func(i, j int) { full[i], full[j] = full[j], full[i] }) + + var packables, unpackables []Version + for _, v := range full { + if v.packable { + packables = append(packables, v) + } else { + unpackables = append(unpackables, v) + } + } + if len(packables) == 0 { + t.Fatal("no packable versions in grid; the fast path is untested") + } + if len(unpackables) == 0 { + t.Fatal("every grid version is packable; the fallback boundary is untested") + } + + vs := append([]Version{}, packables[:min(1200, len(packables))]...) + vs = append(vs, unpackables[:min(400, len(unpackables))]...) + t.Logf("grid: %d versions (%d packable); sampled %d packable + %d unpackable", + len(full), len(packables), min(1200, len(packables)), min(400, len(unpackables))) + + mismatches := 0 + for i := range vs { + for j := range vs { + got := vs[i].Compare(vs[j]) + want := compareSlow(vs[i], vs[j]) + if got != want { + mismatches++ + if mismatches <= 20 { + t.Errorf("Compare(%q, %q) = %d, slow path says %d", + vs[i].Original(), vs[j].Original(), got, want) + } + } + } + } + if mismatches > 0 { + t.Fatalf("%d mismatching pairs", mismatches) + } +} + +// TestPackedLimits pins the exact packability boundary of every field. +func TestPackedLimits(t *testing.T) { + cases := []struct { + v string + want bool + }{ + {"1.2.3", true}, + {"0", true}, + {"0!1.2.3", true}, // a WRITTEN zero epoch packs + {"1.2.3.4.5.6.0.0", true}, // 8 written segments strip to 6 + {"1.2.3.4.5.0.0", true}, // 7 written segments strip to 5 + {"1.0a", true}, + {"1.0rc1", true}, + {"1.0.post1", true}, + {"1.0.dev20240101", true}, + {"1.2.3.4.5.6", true}, + {"1.2.3.4.5.6.7", false}, // 7 segments + {"1.2.3.4.5.6.0", true}, // trailing zero strips to 6 + {"4294967295.0", true}, // 2^32-1 fits + {"4294967296.0", false}, // 2^32 does not + {"1!1.0", false}, // epoch + {"1.0+local", false}, // local + {"1.0a1048575", true}, // preN 2^20-1 + {"1.0a1048576", false}, // preN 2^20 + {"1.0.post16383", true}, // postN 2^14-1 + {"1.0.post16384", false}, // postN 2^14 + {"1.0.dev33554431", true}, // devN 2^25-1 + {"1.0.dev33554432", false}, // devN 2^25 + {"99999999999999999999.0", false}, // > 2^64 segment + } + for _, c := range cases { + v := MustParse(c.v) + if v.packable != c.want { + t.Errorf("packable(%q) = %v, want %v", c.v, v.packable, c.want) + } + } +} + +// TestPackVersionRefusesEmptyRelease pins the packer-local invariant: an +// empty release means a zero-value Version, which must sort below every real +// version, and packing it would instead give it version "0"'s key. Parse is +// currently the only caller and never passes one, so this can only be tested +// by calling the packer directly -- which is the point: the invariant must +// not depend on who calls it next. +func TestPackVersionRefusesEmptyRelease(t *testing.T) { + var ln letterNumber + if _, ok := packVersion(part.BigInt{}, nil, ln, ln, ln, ""); ok { + t.Fatal("packVersion packed an empty release; a zero-value Version would compare equal to version 0") + } +} + +// TestCompareSharedVersionCopiesRace exercises the historical data race: +// go-version v0.0.2's Parts.Normalize leaves len < cap on the key's release +// slice, and Parts.Padding appended into that spare capacity in place, so two +// goroutines comparing by-value COPIES of one Version raced on its backing +// array. Compare now pads into fresh slices (padParts), making a Version +// safely shareable. Run under -race; the unpackable locals force the general +// path where the race lived. +func TestCompareSharedVersionCopiesRace(t *testing.T) { + // Trailing zero stripped by Normalize: key release len 2, cap 3. + shared := MustParse("1.2.0+shared") + // Longer release forces Padding of shared's key from 2 toward 4. + longer := MustParse("1.2.3.4+other") + + var wg sync.WaitGroup + for g := 0; g < 8; g++ { + wg.Add(1) + go func() { + defer wg.Done() + v := shared // by-value copy, shares the key's backing array + o := longer + for i := 0; i < 200; i++ { + if got := v.Compare(o); got != -1 { + t.Errorf("Compare = %d, want -1", got) + return + } + } + }() + } + wg.Wait() +} + +// Benchmarks. The "Packed" benchmarks take the integer fast path; the "Slow" +// ones force the general path over the same versions, which is byte-for-byte +// the pre-spike code (modulo padParts vs Parts.Padding). +func benchPairs() (a, b Version) { + return MustParse("2.31.0"), MustParse("2.30.5") +} + +func BenchmarkComparePacked(b *testing.B) { + x, y := benchPairs() + b.ReportAllocs() + for i := 0; i < b.N; i++ { + if x.Compare(y) != 1 { + b.Fatal("wrong answer") + } + } +} + +func BenchmarkCompareSlow(b *testing.B) { + x, y := benchPairs() + x.packable = false + y.packable = false + b.ReportAllocs() + for i := 0; i < b.N; i++ { + if x.Compare(y) != 1 { + b.Fatal("wrong answer") + } + } +} + +func BenchmarkComparePackedEqual(b *testing.B) { + x := MustParse("1.24.0") + y := MustParse("1.24") + b.ReportAllocs() + for i := 0; i < b.N; i++ { + if x.Compare(y) != 0 { + b.Fatal("wrong answer") + } + } +} + +func BenchmarkCompareSlowEqual(b *testing.B) { + x := MustParse("1.24.0") + y := MustParse("1.24") + x.packable = false + y.packable = false + b.ReportAllocs() + for i := 0; i < b.N; i++ { + if x.Compare(y) != 0 { + b.Fatal("wrong answer") + } + } +} + +// BenchmarkSortVersions sorts a realistic mixed slice, the shape consumers +// actually pay for. +func sortInput(b *testing.B) []Version { + var vs []Version + for maj := 0; maj < 4; maj++ { + for min := 0; min < 25; min++ { + vs = append(vs, MustParse(fmt.Sprintf("%d.%d.%d", maj, min, (maj*7+min)%5))) + vs = append(vs, MustParse(fmt.Sprintf("%d.%d.0rc%d", maj, min+1, min%3+1))) + vs = append(vs, MustParse(fmt.Sprintf("%d.%d.0.dev%d", maj, min+1, 20240100+min))) + } + } + return vs +} + +func BenchmarkSortVersionsPacked(b *testing.B) { + src := sortInput(b) + buf := make([]Version, len(src)) + b.ReportAllocs() + b.ResetTimer() + for i := 0; i < b.N; i++ { + copy(buf, src) + sort.Sort(SortedVersions(buf)) + } +} + +func BenchmarkSortVersionsSlow(b *testing.B) { + src := sortInput(b) + for i := range src { + src[i].packable = false + } + buf := make([]Version, len(src)) + b.ReportAllocs() + b.ResetTimer() + for i := 0; i < b.N; i++ { + copy(buf, src) + sort.Sort(SortedVersions(buf)) + } +} + +func BenchmarkParse(b *testing.B) { + b.ReportAllocs() + for i := 0; i < b.N; i++ { + if _, err := Parse("2.31.0.post1"); err != nil { + b.Fatal(err) + } + } +} diff --git a/version/testdata/pypa-26.2-corpus-sample.ranked.gz b/version/testdata/pypa-26.2-corpus-sample.ranked.gz new file mode 100644 index 0000000..832a2a2 Binary files /dev/null and b/version/testdata/pypa-26.2-corpus-sample.ranked.gz differ diff --git a/version/testdata/pypa-26.2-grid.ranked.gz b/version/testdata/pypa-26.2-grid.ranked.gz new file mode 100644 index 0000000..e613311 Binary files /dev/null and b/version/testdata/pypa-26.2-grid.ranked.gz differ diff --git a/version/version.go b/version/version.go index 77bd29b..f8529b0 100644 --- a/version/version.go +++ b/version/version.go @@ -62,6 +62,13 @@ type Version struct { local string key key original string + + // packed is a fixed-size integer encoding of key, valid when packable is + // true. See packed.go. Compare uses it to order two packable versions + // with a handful of integer comparisons instead of the allocating + // interface-driven path through key. + packed packedKey + packable bool } type key struct { @@ -236,6 +243,8 @@ func Parse(v string) (Version, error) { number: devN, } + packed, packable := packVersion(epoch, release, pre, post, dev, local) + return Version{ epoch: epoch, release: release, @@ -245,6 +254,8 @@ func Parse(v string) (Version, error) { local: local, key: cmpkey(epoch, release, pre, post, dev, local), original: v, + packed: packed, + packable: packable, }, nil } @@ -303,11 +314,35 @@ func cmpkey(epoch part.BigInt, release []part.BigInt, pre, post, dev letterNumbe // returns -1, 0, or 1 if this version is smaller, equal, // or larger than the other version, respectively. func (v Version) Compare(other Version) int { - // A quick, efficient equality check - if v.String() == other.String() { - return 0 + return compareVersions(&v, &other) +} + +// compareVersions is Compare's whole implementation, on pointers. Version is +// a large struct (~392 bytes), so internal callers that already hold two +// Versions in a slice -- SortedVersions.Less above all, which sits inside +// sort's O(n log n) comparison loop -- go through this directly rather than +// copying both structs per comparison just to read a 33-byte packed key. +// It never writes through either pointer; that read-only property is what +// keeps a parsed Version safely shareable across goroutines (see padParts). +func compareVersions(v, other *Version) int { + // The packed fast path: when both versions carry a packed key, a few + // integer comparisons decide the whole ordering. The packed key is a + // complete encoding of the comparison key for packable versions -- see + // packed.go -- so this needs no fallback tie-break. + if v.packable && other.packable { + return v.packed.compare(other.packed) } + // There is deliberately NO String()==String() equality fast path here. + // It rendered both sides to fresh strings on every call -- two + // bytes.Buffer round trips through fmt -- and with the packed path in + // place it could only ever serve pairs where at least one side is + // unpackable. For those pairs the key comparison below returns 0 for + // exactly the same inputs, without the two allocations. Removing it was + // measured alone (against go-pyresolver's resolver benchmark, production + // snapshot) at 1.18-1.51x warm, and is pure simplification once the + // packed key exists. + // ⚠️ An uninitialized Version cannot go through key comparison at all. Its // key's pre/post/dev/local are NIL Part interfaces, and go-version's // Parts.IsAny ranges over the elements calling p.IsAny() with no nil check @@ -346,13 +381,35 @@ func (v Version) Compare(other Version) int { // real.Compare(Version{}) dereferenced a nil part and crashed while // Version{}.Compare(real) returned -1, because only the k1 side was ever // actually padded. That asymmetry is the tell. + // ⚠️ padParts, not Parts.Padding. go-version v0.0.2's Parts.Normalize + // reslices (ret = ret[:i]) leaving len < cap, and Parts.Padding appends + // into that spare capacity IN PLACE -- so a by-value copy of a Version + // shares a backing array with its original, and two goroutines comparing + // copies of the same version race on it. Padding into a fresh slice makes + // Compare read-only on both receivers, which is what lets a Version be + // shared across goroutines. n := max(len(k1.release), len(k2.release)) - k1.release = k1.release.Padding(n, part.Zero) - k2.release = k2.release.Padding(n, part.Zero) + k1.release = padParts(k1.release, n) + k2.release = padParts(k2.release, n) return k1.compare(k2) } +// padParts returns parts extended with part.Zero to size elements, never +// writing through parts' own backing array. See the caller for why appending +// in place (Parts.Padding) is a data race. +func padParts(parts part.Parts, size int) part.Parts { + if len(parts) >= size { + return parts + } + padded := make(part.Parts, size) + copy(padded, parts) + for i := len(parts); i < size; i++ { + padded[i] = part.Zero + } + return padded +} + // Equal tests if two versions are equal. func (v Version) Equal(o Version) bool { return v.Compare(o) == 0 @@ -400,8 +457,10 @@ func (v Version) String() string { // *recovers* it: `fmt.Errorf("%s", v)` yields a message containing // "%!s(PANIC=String method: ...)" and reports no error, so the bug is // swallowed at exactly the call sites most likely to hit it. A direct call - // crashes instead. Compare() also calls String() as its fast path, so this - // one line is what made all six comparison methods panic as well. + // crashes instead. (Compare() historically called String() as its fast + // path, which is how this one line once made all six comparison methods + // panic as well; that fast path is gone, but the guard here still matters + // for every direct rendering call.) writeRelease(&buf, v.release) // Pre-release @@ -561,10 +620,10 @@ func (s SortedVersions) Len() int { return len(s) } func (s SortedVersions) Less(i, j int) bool { - a := s[i] - b := s[j] - - return a.LessThan(b) + // Compare through pointers: this sits inside sort's comparison loop, and + // going through the value-receiver methods would copy four ~392-byte + // structs per comparison to read 33 bytes of packed key. + return compareVersions(&s[i], &s[j]) < 0 } func (s SortedVersions) Swap(i, j int) { s[i], s[j] = s[j], s[i]