From 12b4218bbd5e01917713c8114bcdfbcbca4b8ac4 Mon Sep 17 00:00:00 2001 From: Jonathan Yoder Date: Mon, 10 Aug 2026 11:09:46 -0400 Subject: [PATCH 1/7] Add the public API PEP 440/508 conformance assertions need Roughly 80% of pypa/packaging's test_specifiers.py cases could not be written against this module's public surface -- not because they were Python-specific, but because the corresponding Go API did not exist. Only the *set* was public, exposing just Check and String. Adds: - Specifier, the exported singular specifier, with Operator/Version/ Original/String/Check/Contains/ContainsVersion/Filter/FilterVersions/ PreReleases/Equal. - PreReleases, a three-state pre-release policy (Auto/Include/Exclude) with WithPreReleases, usable at construction and per call. - Filter and Contains on both types, implementing PEP 440 candidate SELECTION. Contains is defined as "Filter of one item is non-empty", exactly as upstream defines it, so the two cannot disagree. - A string-operand query path, which finally makes ===lolwat expressible: Check takes a Version and Parse("lolwat") fails. - FilterBy, upstream's key= parameter, as a generic free function. - Specifiers Len/List/Equal/And/ContainsInstalled, NewSpecifiersFrom. - marker.Environment.With/Lookup and marker.VariableNames, the seam a PARTIAL marker environment needs. Two behavior changes worth reviewing carefully. WithPreRelease(true) used to set a flag that made Version.IsPreRelease report false for a version that plainly is a pre-release, disabling the guards in specifierLessThan/specifierGreaterThan and making <2 match 2.0.dev1. That conflated candidate SELECTION with MATCHING. Measured against pypa/packaging 26.2, Specifier("<2").contains("2.0.dev1") is False under every pre-release policy -- the guard is part of what "<" means, not a policy. The flag is removed, so IsPreRelease is now a property of the version alone. One existing assertion pinned the old behavior and is corrected. Specifiers.String() now renders each member normalized rather than echoing input text, so NewSpecifiers("< 2").String() is "<2". Requirement.String() is unaffected: internal/pep508's normalizeSpecifierClause already stripped that whitespace before version.NewSpecifiers saw it, so the two levels previously disagreed. Also fixes NewSpecifiers("") (now the universal set, the empty-input arm that survived 0.3.0's zero-value fix) and the six MustParse calls on the matching path, which no longer panic on an uninterpretable operand. Every expected value was measured against pypa/packaging 26.2 rather than derived from the PEP text. Refs rstudio/package-manager#19383 Co-Authored-By: Claude Opus 5 (1M context) --- CHANGELOG.md | 120 ++++++ marker/environment.go | 93 +++++ marker/partial_environment_test.go | 173 +++++++++ version/operand_hardening_test.go | 110 ++++++ version/prerelease.go | 102 ++++++ version/prerelease_policy_test.go | 441 ++++++++++++++++++++++ version/specifier.go | 318 ++++++++++++---- version/specifier_api_test.go | 343 +++++++++++++++++ version/specifier_option.go | 22 +- version/specifier_query.go | 569 +++++++++++++++++++++++++++++ version/specifier_test.go | 17 +- version/version.go | 46 ++- 12 files changed, 2269 insertions(+), 85 deletions(-) create mode 100644 marker/partial_environment_test.go create mode 100644 version/operand_hardening_test.go create mode 100644 version/prerelease.go create mode 100644 version/prerelease_policy_test.go create mode 100644 version/specifier_api_test.go create mode 100644 version/specifier_query.go diff --git a/CHANGELOG.md b/CHANGELOG.md index e5b6ce6..b38be99 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,126 @@ mistaken for a safe patch upgrade. ## [Unreleased] +### Breaking + +- `WithPreRelease(true)` no longer suppresses the operator-level pre-release guards. + + It used to set a flag on the `Version` being tested that made + `Version.IsPreRelease()` report **false for a version that plainly is a pre-release**, + which disabled the guards inside `specifierLessThan` and `specifierGreaterThan`. The + observable effect was that `<2` matched `2.0.dev1`. Measured against + `pypa/packaging` 26.2, `Specifier("<2").contains("2.0.dev1")` is `False` with + `prereleases=True`, with `prereleases=False`, and with the default — the guard is not + a pre-release *policy* at all, it is part of what `<` means. + + That flag conflated two different things. PEP 440's pre-release rule governs which + candidates an installer **offers**; the operator guards govern which versions a + specifier **matches**. A pre-release does satisfy `>=1.0` — verified against the + reference implementation — it is merely passed over while a final release is also + available. The flag has been removed, so `Version.IsPreRelease()` is now a property of + the version alone and nothing can override it. + + One existing assertion pinned the old behavior (`TestVersion_CheckWithPreRelease` + asserted `2.0a1` satisfies `<2` under `WithPreRelease(true)`) and has been corrected. + + `WithPreRelease` is now deprecated in favor of `WithPreReleases`. `WithPreRelease(true)` + maps to `PreReleasesInclude` and `WithPreRelease(false)` to `PreReleasesAuto` — `false` + never meant "exclude" here, it meant "no override". + +- `Specifiers.String()` now renders each specifier normalized instead of echoing the + input text. `NewSpecifiers("< 2").String()` was `"< 2"` and is now `"<2"`, matching + upstream's `str(SpecifierSet("< 2"))`. + + `Requirement.String()` is unaffected: `internal/pep508`'s `normalizeSpecifierClause` + already strips that whitespace before the string reaches `version.NewSpecifiers`, so + the two levels previously disagreed and now agree. The `requirement/` conformance + suite passes unchanged. + + ⚠️ Input **order** is still preserved, which upstream does not do — it sorts its + members, so `SpecifierSet(">=1,<2")` renders as `"<2,>=1"`. Left as a deliberate + divergence: the OR-of-ANDs shape this type carries for the R path (`a || b`) has no + upstream counterpart to sort within. + +### Added + +- `Specifier`, the exported **singular** specifier, with `Operator()`, `Version()`, + `Original()`, `String()`, `Check()`, `Contains()`, `ContainsVersion()`, `Filter()`, + `FilterVersions()`, `PreReleases()` and `Equal()`. Built with `NewSpecifier`, or read + off a set with `Specifiers.List()`. Previously only the *set* was public, exposing + just `Check` and `String`. + + `Specifier.Version()` returns the operand **as written** rather than normalized + (`NewSpecifier(">= v1.0 ").Version()` is `"v1.0"`), which is what upstream does. + `Equal` canonicalizes instead: `==2.8.0` equals `==2.8`, but `~=1.18.0` does **not** + equal `~=1.18`, because trailing zeros change which versions `~=` accepts. + +- `PreReleases`, a three-state pre-release policy (`PreReleasesAuto`, + `PreReleasesInclude`, `PreReleasesExclude`) with the `WithPreReleases` option, which + works both as a `SpecifierOption` at construction and as a `FilterOption` overriding it + for a single call. `PreReleasesAuto` is the zero value and derives the policy from the + specifier per PEP 440, which a bool cannot express. + + ⚠️ The set-level and specifier-level derivations are deliberately asymmetric, as + upstream's are: `Specifier(">=1.0").PreReleases()` is `PreReleasesExclude` while + `NewSpecifiers(">=1.0").PreReleases()` is `PreReleasesAuto`. That is what lets a set + fall back to offering a pre-release when nothing else matched. + +- `Filter` / `Contains` on both types, implementing PEP 440 candidate **selection**: + pre-releases are held back while any final release matches, and offered when none + does. `Contains` is defined as "`Filter` of one item is non-empty", exactly as + upstream defines it, so the two cannot disagree. + +- A **string-operand** query path. `Contains` takes a raw `string`, so a non-PEP 440 + operand is finally expressible: `NewSpecifier("===lolwat").Contains("lolwat")` is + true. This was previously impossible — `Check` takes a `version.Version` and + `version.Parse("lolwat")` fails, so there was no way to pass the value in. + + `Contains` (string) and `ContainsVersion` (parsed) differ only for `===`, which + compares the caller's spelling: `===1.1` contains `Version("1.01")` but not the + *string* `"1.01"`. That distinction is upstream's and is now testable. + +- `FilterBy`, a generic free function providing upstream's `key=` parameter for + filtering a slice of arbitrary values by a version field. It is a function rather than + a method because Go methods cannot take type parameters. + +- `Specifiers.Len()`, `Specifiers.List()`, `Specifiers.Equal()`, `Specifiers.And()`, + `Specifiers.ContainsInstalled()` and `NewSpecifiersFrom()`. + + `And` combines the two sets' pre-release policies rather than dropping them, and + returns `ErrPreReleaseConflict` when they contradict (one `Include`, one `Exclude`), + where upstream raises `ValueError`. Like upstream it keeps duplicates — + `len(SpecifierSet(">=1.0") & SpecifierSet(">=1.0"))` is 2 in packaging 26.2 — while + `Equal` is blind to order and duplicates. + +- `marker.Environment.With(map[string]string)`, `Environment.Lookup(name)` and + `marker.VariableNames()`: the override seam a **partial** marker environment needs. + + Upstream's `Marker.evaluate` takes a partial dict and keeps the live interpreter's + value for every key the caller left out. The naive Go translation is a struct literal, + which zero-fills instead — so `Environment{OsName: "foo"}` silently sets + `python_version` to `""` and **changes the answer** of any marker touching it, with no + error reported. `With` overrides onto an explicit base, preserving the distinction + between "set to the empty string" and "never mentioned". An unrecognized variable name + is an error rather than a silent no-op. + +### Fixed + +- `NewSpecifiers("")` is now the universal set instead of an error. Upstream treats + `SpecifierSet('')` as valid, of length zero, and containing every version. The 0.3.0 + fix covered only the zero-value/no-groups arm; this is the empty-input arm that + survived it. + +- The six `MustParse` calls on the matching hot path (`version/specifier.go`) no longer + panic on an operand that is not a valid version; a comparison that cannot be made + yields no match. + + ⚠️ Honest scope: these were **not** reachable through the public API before this + change, and are not now — every operand except `===` is validated at construction, and + `===` never reaches those functions. But "unreachable" was a property of the *callers*, + and the exported `Specifier` plus `Filter` are new callers that drive them with + whatever operand they hold. The regression test builds the shape directly and was + verified to panic without the fix. + ## [0.4.0] - 2026-08-10 ### Breaking diff --git a/marker/environment.go b/marker/environment.go index e1e9d8c..6c5db01 100644 --- a/marker/environment.go +++ b/marker/environment.go @@ -34,6 +34,99 @@ type Environment struct { ImplementationVersion string // "3.11.4" } +// ErrUnknownMarkerVariable is returned by Environment.With and +// Environment.Lookup for a name that is not one of the 11 PEP 508 marker +// variables. +var ErrUnknownMarkerVariable = errors.New("unknown PEP 508 marker variable") + +// VariableNames returns the 11 PEP 508 marker variable names, in the order the +// Environment fields declare them. +func VariableNames() []string { + return []string{ + "os_name", + "sys_platform", + "platform_machine", + "platform_python_implementation", + "platform_release", + "platform_system", + "platform_version", + "python_version", + "python_full_version", + "implementation_name", + "implementation_version", + } +} + +// Lookup returns the value of a PEP 508 marker variable by its PEP 508 name +// ("os_name", "python_version", ...), and ErrUnknownMarkerVariable for +// anything else. +func (env Environment) Lookup(name string) (string, error) { + if !isMarkerVariable(name) { + return "", fmt.Errorf("%w: %q", ErrUnknownMarkerVariable, name) + } + return envVarValue(name, env), nil +} + +// With returns a copy of env with the named marker variables replaced. It is +// the override seam a partial marker environment needs. +// +// # Why this exists rather than a bare struct literal +// +// pypa/packaging's `Marker.evaluate` takes a PARTIAL dict — `{"os_name": +// "foo"}` — and falls back to the live interpreter's values for every key the +// caller left out. Environment is a struct, so the equivalent-looking Go +// literal `Environment{OsName: "foo"}` zero-fills the other ten fields +// instead. That is not the same evaluation: `python_version` becomes "", so a +// marker like `python_version >= "3.8"` silently flips its answer, and nothing +// reports an error. Overriding onto an explicit base keeps the distinction +// between "this variable is set to the empty string" and "this variable was +// never mentioned". +// +// An unrecognized name is an error rather than a silent no-op, because a typo +// in a variable name would otherwise produce an evaluation against the base +// value and look like it worked. +func (env Environment) With(overrides map[string]string) (Environment, error) { + out := env + for name, value := range overrides { + switch name { + case "os_name": + out.OsName = value + case "sys_platform": + out.SysPlatform = value + case "platform_machine": + out.PlatformMachine = value + case "platform_python_implementation": + out.PlatformPythonImplementation = value + case "platform_release": + out.PlatformRelease = value + case "platform_system": + out.PlatformSystem = value + case "platform_version": + out.PlatformVersion = value + case "python_version": + out.PythonVersion = value + case "python_full_version": + out.PythonFullVersion = value + case "implementation_name": + out.ImplementationName = value + case "implementation_version": + out.ImplementationVersion = value + default: + return Environment{}, fmt.Errorf("%w: %q", ErrUnknownMarkerVariable, name) + } + } + return out, nil +} + +func isMarkerVariable(name string) bool { + for _, known := range VariableNames() { + if known == name { + return true + } + } + return false +} + // InterpreterIdentity carries the marker fields a tags.Target cannot derive: // the concrete interpreter identity and its full version. // tags.Target.Implementation is only "cp"|"py" - a wheel-compatibility diff --git a/marker/partial_environment_test.go b/marker/partial_environment_test.go new file mode 100644 index 0000000..b41adca --- /dev/null +++ b/marker/partial_environment_test.go @@ -0,0 +1,173 @@ +// SPDX-License-Identifier: Apache-2.0 OR MIT + +// Tests for the partial-marker-environment override seam added for +// rstudio/package-manager#19383. + +package marker + +import ( + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// baseEnvironment is a fully-populated environment to override onto, standing +// in for what upstream gets from the live interpreter. +func baseEnvironment() Environment { + return Environment{ + OsName: "posix", + SysPlatform: "linux", + PlatformMachine: "x86_64", + PlatformPythonImplementation: "CPython", + PlatformRelease: "6.1.0", + PlatformSystem: "Linux", + PlatformVersion: "#1 SMP", + PythonVersion: "3.11", + PythonFullVersion: "3.11.4", + ImplementationName: "cpython", + ImplementationVersion: "3.11.4", + } +} + +// ⚠️ THE reason this seam exists. Upstream's Marker.evaluate takes a PARTIAL +// dict and keeps the live interpreter's value for every unmentioned key. The +// naive Go translation is a struct literal, which zero-fills instead -- so +// `python_version` silently becomes "" and a marker that mentions it changes +// its answer with no error reported. +// +// The two halves of this test are the same override expressed both ways, and +// they must NOT agree. +func TestStructLiteralZeroFillIsNotAPartialEnvironment(t *testing.T) { + m, err := Parse(`os_name == "foo" and python_version >= "3.8"`) + require.NoError(t, err) + + // The zero-filling trap: python_version is "", so the marker is false. + naive := Environment{OsName: "foo"} + assert.False(t, m.Evaluate(naive, nil), + "a struct literal zero-fills python_version, changing the answer") + + // The override seam: everything the caller did not mention is preserved. + partial, err := baseEnvironment().With(map[string]string{"os_name": "foo"}) + require.NoError(t, err) + assert.True(t, m.Evaluate(partial, nil), + "With must preserve the base value for unmentioned variables") +} + +// Every one of the 11 PEP 508 variables must be settable by name and readable +// back. This is a bijection check across VariableNames, With's switch and +// envVarValue's switch: the three are separate switches on the same names, and +// the failure mode of drift is a variable that silently cannot be overridden. +func TestWithAndLookupCoverEveryMarkerVariable(t *testing.T) { + names := VariableNames() + assert.Len(t, names, 11, "PEP 508 defines 11 marker variables") + + for _, name := range names { + t.Run(name, func(t *testing.T) { + const sentinel = "OVERRIDDEN" + + env, err := baseEnvironment().With(map[string]string{name: sentinel}) + require.NoError(t, err) + + got, err := env.Lookup(name) + require.NoError(t, err) + assert.Equal(t, sentinel, got, "With must set the variable Lookup reads") + + // No other variable may have moved. + for _, other := range names { + if other == name { + continue + } + want, err := baseEnvironment().Lookup(other) + require.NoError(t, err) + actual, err := env.Lookup(other) + require.NoError(t, err) + assert.Equal(t, want, actual, "overriding %q must not touch %q", name, other) + } + }) + } +} + +// An override actually reaches evaluation for every variable, not just Lookup. +func TestOverrideReachesEvaluation(t *testing.T) { + for _, name := range VariableNames() { + t.Run(name, func(t *testing.T) { + // A value that no base field holds, and that is not version-shaped, + // so the comparison takes the string path uniformly. + const sentinel = "zzsentinelzz" + + m, err := Parse(name + ` == "` + sentinel + `"`) + require.NoError(t, err) + + base := baseEnvironment() + assert.False(t, m.Evaluate(base, nil), "base must not already match") + + env, err := base.With(map[string]string{name: sentinel}) + require.NoError(t, err) + assert.True(t, m.Evaluate(env, nil), "override must reach evaluation") + }) + } +} + +// A typo in a variable name must be an error, not a silent no-op that +// evaluates against the base value and looks like it worked. +func TestWithRejectsUnknownVariable(t *testing.T) { + for _, name := range []string{"", "os-name", "osname", "OS_NAME", "extra", "platform_machin"} { + t.Run(name, func(t *testing.T) { + _, err := baseEnvironment().With(map[string]string{name: "x"}) + assert.ErrorIs(t, err, ErrUnknownMarkerVariable) + }) + } +} + +// `extra` is deliberately NOT a marker-environment variable: it is bound from +// the active-extras list passed to Evaluate, not from the environment. +func TestExtraIsNotAnEnvironmentVariable(t *testing.T) { + assert.NotContains(t, VariableNames(), "extra") + + _, err := baseEnvironment().Lookup("extra") + assert.ErrorIs(t, err, ErrUnknownMarkerVariable) + + m, err := Parse(`extra == "docs"`) + require.NoError(t, err) + assert.False(t, m.Evaluate(baseEnvironment(), nil)) + assert.True(t, m.Evaluate(baseEnvironment(), []string{"docs"})) +} + +// With must not mutate its receiver, and must tolerate an empty or nil map. +func TestWithDoesNotMutateReceiver(t *testing.T) { + base := baseEnvironment() + + derived, err := base.With(map[string]string{"os_name": "nt", "sys_platform": "win32"}) + require.NoError(t, err) + + assert.Equal(t, baseEnvironment(), base, "receiver must be unchanged") + assert.Equal(t, "nt", derived.OsName) + assert.Equal(t, "win32", derived.SysPlatform) + + same, err := base.With(nil) + require.NoError(t, err) + assert.Equal(t, base, same) + + same, err = base.With(map[string]string{}) + require.NoError(t, err) + assert.Equal(t, base, same) +} + +// Overriding to the empty string is a real override, distinguishable from +// leaving a variable unmentioned. That distinction is the whole point of the +// seam, so pin it. +func TestOverrideToEmptyStringIsDistinctFromUnmentioned(t *testing.T) { + m, err := Parse(`platform_release == ""`) + require.NoError(t, err) + + base := baseEnvironment() + assert.False(t, m.Evaluate(base, nil)) + + cleared, err := base.With(map[string]string{"platform_release": ""}) + require.NoError(t, err) + assert.True(t, m.Evaluate(cleared, nil)) + + // And the unmentioned variables are still their base values, not "". + assert.Equal(t, "3.11", cleared.PythonVersion) +} diff --git a/version/operand_hardening_test.go b/version/operand_hardening_test.go new file mode 100644 index 0000000..13acb80 --- /dev/null +++ b/version/operand_hardening_test.go @@ -0,0 +1,110 @@ +// SPDX-License-Identifier: Apache-2.0 OR MIT + +// Regression tests for the six MustParse calls the matching functions used to +// make on unvalidated operands (rstudio/package-manager#19383). +// +// ⚠️ Honest scope note. These panics were NOT reachable through the public API +// before this change, and are not now: every operand except `===` is validated +// at construction, and `===` never reaches these functions. That is why the +// tests below build a Specifier struct directly -- they can only be written +// from inside the package. What changed is that "unreachable" was a property of +// the callers, and the exported Specifier type plus Filter added new callers +// that drive these functions with whatever operand they hold. The test pins the +// contract (a bad operand yields no match) so a future caller cannot +// reintroduce a panic on remote-supplied input. + +package version + +import ( + "testing" + + "github.com/stretchr/testify/assert" +) + +// operandPanicShapes are the (operator, operand) pairs that reached a MustParse +// with a non-version operand. Each entry names the function it exercises. +func operandPanicShapes() []struct { + name string + op string + fn operatorFunc +} { + return []struct { + name string + op string + fn operatorFunc + }{ + {"specifierEqual", "==", specifierEqual}, + {"specifierNotEqual", "!=", specifierNotEqual}, + {"specifierLessThan", "<", specifierLessThan}, + {"specifierGreaterThan", ">", specifierGreaterThan}, + {"specifierLessThanEqual", "<=", specifierLessThanEqual}, + {"specifierGreaterThanEqual", ">=", specifierGreaterThanEqual}, + {"specifierCompatible", "~=", specifierCompatible}, + } +} + +func TestUnparseableOperandDoesNotPanic(t *testing.T) { + prospective := MustParse("1.2.3") + + for _, shape := range operandPanicShapes() { + for _, operand := range []string{"lolwat", "", "not a version", "1.2.3.4.5-garbage"} { + t.Run(shape.name+"__"+operand, func(t *testing.T) { + s := Specifier{op: shape.op, operand: operand, fn: shape.fn} + assert.NotPanics(t, func() { + // A comparison that cannot be made is not a match. It + // must not be a match, either: admitting a version on the + // strength of an uninterpretable operand is worse than + // rejecting it. + got := s.Check(prospective) + if shape.op == "!=" { + // Not-equal negates equal, which returns false, so the + // negation is true. Documented rather than asserted + // false, so the inversion is visible. + assert.True(t, got) + return + } + assert.False(t, got) + }) + }) + } + } +} + +// Filter drives the matching functions directly, so it is the realistic path a +// bad operand would arrive by. +func TestFilterWithUnparseableOperandDoesNotPanic(t *testing.T) { + for _, shape := range operandPanicShapes() { + t.Run(shape.name, func(t *testing.T) { + s := Specifier{op: shape.op, operand: "lolwat", fn: shape.fn} + assert.NotPanics(t, func() { + s.Filter([]string{"1.0", "2.0a1", "also not a version"}) + }) + }) + } +} + +// The whole set path, likewise. +func TestSpecifiersFilterWithUnparseableOperandDoesNotPanic(t *testing.T) { + ss := Specifiers{specifiers: [][]Specifier{{ + {op: ">=", operand: "lolwat", fn: specifierGreaterThanEqual}, + {op: "<", operand: "1.0", fn: specifierLessThan}, + }}} + assert.NotPanics(t, func() { + assert.Empty(t, ss.Filter([]string{"0.5", "2.0"})) + }) +} + +// A zero-value Version must not panic when it reaches a matching function +// either: it is the other side of the same landmine, and fmt RECOVERS a +// panicking String method, so a crash here would be swallowed at exactly the +// call sites most likely to hit it. +func TestZeroValueProspectiveDoesNotPanic(t *testing.T) { + for _, shape := range operandPanicShapes() { + t.Run(shape.name, func(t *testing.T) { + s := Specifier{op: shape.op, operand: "1.0", fn: shape.fn} + assert.NotPanics(t, func() { + s.Check(Version{}) + }) + }) + } +} diff --git a/version/prerelease.go b/version/prerelease.go new file mode 100644 index 0000000..d195fde --- /dev/null +++ b/version/prerelease.go @@ -0,0 +1,102 @@ +// SPDX-License-Identifier: Apache-2.0 OR MIT + +package version + +// PreReleases is a three-state pre-release policy, matching the +// `prereleases: bool | None` parameter that pypa/packaging threads through +// `Specifier` and `SpecifierSet`. +// +// # Why three states and not a bool +// +// A bool can say "include pre-releases" and "exclude pre-releases". It cannot +// say "nobody has expressed a preference, so derive one from the specifier +// itself", which is what PEP 440 actually prescribes and what upstream's +// default (`None`) means. All three states behave differently, so collapsing +// `None` into `false` silently answers a question the caller never asked. +// +// # ⚠️ This policy governs SELECTION, not MATCHING +// +// PEP 440's pre-release rule is about which candidates an installer should +// *offer*, not about which versions a specifier *matches*. A pre-release does +// satisfy `>=1.0` — `Specifier(">=1.0").contains("1.5a1")` is true in +// pypa/packaging 26.2, verified — it is merely passed over while a final +// release is also available: +// +// Filter(">=1.0", ["1.5a1"]) -> ["1.5a1"] (nothing else on offer) +// Filter(">=1.0", ["1.5a1", "2.0"]) -> ["2.0"] (a final release wins) +// +// Conflating the two produces real bugs in both directions: an over-strict +// reading drops a pre-release that is the only candidate, and an over-loose +// reading defeats the operator-level guards that are *not* part of this policy +// at all. Those guards live in the comparison operators — `<2` never matches +// `2.0.dev1` and `>2` never matches `2.0.post1`, with any pre-release policy — +// and no value of PreReleases turns them off. +type PreReleases int8 + +const ( + // PreReleasesAuto derives the policy from the specifier, per PEP 440. It + // is the zero value, so a Specifier or Specifiers built without an + // explicit policy autodetects, matching upstream's `prereleases=None` + // default. See Specifier.PreReleases for the derivation. + PreReleasesAuto PreReleases = iota + + // PreReleasesInclude offers pre-releases alongside final releases, + // matching upstream's `prereleases=True`. + PreReleasesInclude + + // PreReleasesExclude never offers pre-releases, even when no final + // release is available, matching upstream's `prereleases=False`. + PreReleasesExclude +) + +// String renders the policy using upstream's spelling of the corresponding +// Python value, so a test failure message lines up with the reference +// implementation's parameter. +func (p PreReleases) String() string { + switch p { + case PreReleasesInclude: + return "true" + case PreReleasesExclude: + return "false" + case PreReleasesAuto: + return "none" + default: + return "unknown" + } +} + +// PreReleaseOption carries a PreReleases policy. It satisfies both +// SpecifierOption (so a policy can be attached when a specifier is built) and +// FilterOption (so a policy can override that one for a single Contains or +// Filter call), which is the same dual role upstream gives its `prereleases` +// parameter on both the constructor and the query methods. +type PreReleaseOption struct{ policy PreReleases } + +// WithPreReleases sets the three-state pre-release policy. It may be passed +// to NewSpecifier / NewSpecifiers as a SpecifierOption, or to Contains / +// Filter as a per-call FilterOption that takes precedence over the policy the +// specifier was built with. +func WithPreReleases(p PreReleases) PreReleaseOption { + return PreReleaseOption{policy: p} +} + +func (o PreReleaseOption) apply(c *conf) { c.preReleases = o.policy } + +func (o PreReleaseOption) applyFilter(fc *filterConf) { fc.preReleases = o.policy } + +// FilterOption configures a single Contains or Filter call. +type FilterOption interface { + applyFilter(*filterConf) +} + +type filterConf struct { + preReleases PreReleases +} + +func newFilterConf(opts []FilterOption) filterConf { + var fc filterConf + for _, o := range opts { + o.applyFilter(&fc) + } + return fc +} diff --git a/version/prerelease_policy_test.go b/version/prerelease_policy_test.go new file mode 100644 index 0000000..75cf920 --- /dev/null +++ b/version/prerelease_policy_test.go @@ -0,0 +1,441 @@ +// SPDX-License-Identifier: Apache-2.0 OR MIT + +// Unit tests for the three-state pre-release policy added for +// rstudio/package-manager#19383. +// +// Every expected value was measured against pypa/packaging 26.2. + +package version + +import ( + "fmt" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// TestSpecifier_PreReleases_Autodetect pins the PEP 440 derivation upstream +// performs when no policy is set. Note the two carve-outs that are easy to get +// backwards: `!=` never implies pre-releases even against a pre-release +// operand, and `===` stays UNRESOLVED because its operand is not a version at +// all. +func TestSpecifier_PreReleases_Autodetect(t *testing.T) { + tests := []struct { + in string + want PreReleases + }{ + {"==1.0", PreReleasesExclude}, + {">=1.0", PreReleasesExclude}, + {"<=1.0", PreReleasesExclude}, + {"~=1.0", PreReleasesExclude}, + {"<1.0", PreReleasesExclude}, + {">1.0", PreReleasesExclude}, + {"!=1.0", PreReleasesExclude}, + {"<1.0.dev1", PreReleasesInclude}, + {">1.0.dev1", PreReleasesInclude}, + {"==1.0.dev1", PreReleasesInclude}, + {">=1.0.dev1", PreReleasesInclude}, + {"<=1.0.dev1", PreReleasesInclude}, + {"~=1.0.dev1", PreReleasesInclude}, + {"==1.0a1.dev1", PreReleasesInclude}, + // `!=` against a pre-release operand still excludes. + {"!=1.0.dev1", PreReleasesExclude}, + // A wildcard `==` cannot name a pre-release, so it excludes. + {"==1.0.*", PreReleasesExclude}, + // An opaque `===` operand leaves the policy unresolved. + {"===lolwat", PreReleasesAuto}, + // ...unless the operand happens to parse as a pre-release version. + {"===1.0.dev1", PreReleasesInclude}, + } + + for _, tt := range tests { + t.Run(tt.in, func(t *testing.T) { + s, err := NewSpecifier(tt.in) + require.NoError(t, err) + assert.Equal(t, tt.want, s.PreReleases()) + }) + } +} + +// An explicit policy short-circuits the derivation entirely. +func TestSpecifier_PreReleases_ExplicitWins(t *testing.T) { + for _, policy := range []PreReleases{PreReleasesInclude, PreReleasesExclude} { + t.Run(policy.String(), func(t *testing.T) { + // ">=1.0" would autodetect Exclude, "<1.0.dev1" Include. + for _, spec := range []string{">=1.0", "<1.0.dev1"} { + s, err := NewSpecifier(spec, WithPreReleases(policy)) + require.NoError(t, err) + assert.Equal(t, policy, s.PreReleases(), "spec %q", spec) + } + }) + } +} + +// TestSpecifiers_PreReleases_Autodetect pins the SET-level derivation, which is +// deliberately asymmetric with the single-specifier one: a set of ordinary +// final-release specifiers resolves to PreReleasesAuto, never to Exclude, even +// though each member alone resolves to Exclude. That asymmetry is upstream's, +// and it is what lets a set fall back to offering a pre-release when nothing +// else matched. +func TestSpecifiers_PreReleases_Autodetect(t *testing.T) { + tests := []struct { + in string + want PreReleases + }{ + {"", PreReleasesAuto}, + {"==1.0", PreReleasesAuto}, + {">=1.0,<2", PreReleasesAuto}, + {"!=1.0.dev1", PreReleasesAuto}, + {"==1.0.*", PreReleasesAuto}, + {"===lolwat", PreReleasesAuto}, + {"<1.0.dev1", PreReleasesInclude}, + {">=1.0,<2.0.dev1", PreReleasesInclude}, + } + + for _, tt := range tests { + t.Run(fmt.Sprintf("%q", tt.in), func(t *testing.T) { + ss, err := NewSpecifiers(tt.in) + require.NoError(t, err) + assert.Equal(t, tt.want, ss.PreReleases()) + }) + } +} + +// ⚠️ THE central distinction. A pre-release DOES satisfy an ordinary +// specifier; PEP 440's rule is about which candidate an installer offers when +// several match, not about which versions the operator matches. Conflating the +// two is what produced the bug this API exists to prevent. +func TestPreReleaseExclusionIsSelectionNotMatching(t *testing.T) { + tests := []struct { + spec string + item string + want bool + }{ + // Queried alone, a pre-release satisfies >= and > -- there is no final + // release to prefer over it. + {">=1.0", "1.5a1", true}, + {">=1.0", "2.0.dev1", true}, + {"==2.0.*", "2.0.dev1", true}, + {"!=1.0.dev1", "1.5a1", true}, + // These false answers come from the OPERATORS, not from the policy: + // `<2` excludes a pre-release of 2, and `>2` excludes a post-release + // of 2, at every policy setting. + {"<2", "2.0.dev1", false}, + {">2", "2.0.post1", false}, + {"!=2.0a1", "2.0a1", false}, + } + + for _, tt := range tests { + t.Run(tt.spec+"__"+tt.item, func(t *testing.T) { + s, err := NewSpecifier(tt.spec) + require.NoError(t, err) + assert.Equal(t, tt.want, s.Contains(tt.item), "Specifier.Contains") + + ss, err := NewSpecifiers(tt.spec) + require.NoError(t, err) + assert.Equal(t, tt.want, ss.Contains(tt.item), "Specifiers.Contains") + }) + } +} + +// No pre-release policy can defeat an operator-level guard. This is the +// regression test for the conflation WithPreRelease(true) used to introduce: +// it set a flag that made Version.IsPreRelease lie, so `<2` matched +// `2.0.dev1`. Measured against packaging 26.2, `<2` contains `2.0.dev1` under +// none of the three policies. +func TestNoPolicyDefeatsTheOperatorGuards(t *testing.T) { + guards := []struct{ spec, item string }{ + {"<2", "2.0.dev1"}, + {"<2", "2.0a1"}, + {"<3.1", "3.1.dev0"}, + {">2", "2.0.post1"}, + {">=2", "2.0.dev1"}, + } + + for _, g := range guards { + for _, policy := range []PreReleases{PreReleasesAuto, PreReleasesInclude, PreReleasesExclude} { + t.Run(g.spec+"__"+g.item+"__"+policy.String(), func(t *testing.T) { + s, err := NewSpecifier(g.spec, WithPreReleases(policy)) + require.NoError(t, err) + assert.False(t, s.Contains(g.item), "constructor policy") + + plain, err := NewSpecifier(g.spec) + require.NoError(t, err) + assert.False(t, plain.Contains(g.item, WithPreReleases(policy)), "per-call policy") + }) + } + } + + // The same, through the deprecated two-state option. + legacy, err := NewSpecifiers("<2", WithPreRelease(true)) + require.NoError(t, err) + assert.False(t, legacy.Check(MustParse("2.0.dev1"))) +} + +func TestSpecifier_Filter(t *testing.T) { + tests := []struct { + name string + spec string + specPre PreReleases + callPre PreReleases + items []string + want []string + }{ + // The PEP 440 preference: a final release wins, a pre-release is + // offered only when nothing else matched. + {"final wins", ">=1.2.3", PreReleasesAuto, PreReleasesAuto, + []string{"1.2", "1.3", "1.5a1"}, []string{"1.3"}}, + {"pre offered when alone", ">=1.2.3", PreReleasesAuto, PreReleasesAuto, + []string{"1.2", "1.5a1"}, []string{"1.5a1"}}, + // An operand that is itself a pre-release autodetects Include, so both + // come through. + {"prerelease operand includes", ">=1.0.dev1", PreReleasesAuto, PreReleasesAuto, + []string{"1.0", "2.0a1"}, []string{"1.0", "2.0a1"}}, + {"per-call exclude overrides", ">=1.0.dev1", PreReleasesAuto, PreReleasesExclude, + []string{"1.0", "2.0a1"}, []string{"1.0"}}, + {"constructor include", ">=1.0.dev1", PreReleasesInclude, PreReleasesAuto, + []string{"1.0", "2.0a1"}, []string{"1.0", "2.0a1"}}, + {"constructor exclude", ">=1.0.dev1", PreReleasesExclude, PreReleasesAuto, + []string{"1.0", "2.0a1"}, []string{"1.0"}}, + {"not-equal drops the pre", "!=2.0a1", PreReleasesAuto, PreReleasesAuto, + []string{"1.0a2", "1.0", "2.0a1"}, []string{"1.0"}}, + {"compatible with pre operand", "~=2.0a1", PreReleasesAuto, PreReleasesAuto, + []string{"1.0", "2.0a1", "3.0a2", "3.0"}, []string{"2.0a1"}}, + // An unparseable string is silently discarded, not an error. + {"invalid alone", ">=1.0", PreReleasesAuto, PreReleasesAuto, + []string{"not a valid version"}, nil}, + {"invalid alongside valid", ">=1.0", PreReleasesAuto, PreReleasesAuto, + []string{"1.0", "not a valid version"}, []string{"1.0"}}, + // Arbitrary equality is the only operator that can match a non-version, + // and it compares the string as written: "1.0" does not match "1.0.0". + {"arbitrary matches token", "===foobar", PreReleasesAuto, PreReleasesAuto, + []string{"foobar", "foo", "bar"}, []string{"foobar"}}, + {"arbitrary is not zero-padded", "===1.0", PreReleasesAuto, PreReleasesAuto, + []string{"1.0", "1.0.0", "2.0"}, []string{"1.0"}}, + {"not-equal rejects invalid", "!=1.0", PreReleasesAuto, PreReleasesAuto, + []string{"1.0", "invalid", "2.0"}, []string{"2.0"}}, + {"wildcard not-equal rejects invalid", "!=2.0.*", PreReleasesAuto, PreReleasesAuto, + []string{"invalid", "foobar", "2.0"}, nil}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + s, err := NewSpecifier(tt.spec, WithPreReleases(tt.specPre)) + require.NoError(t, err) + + got := s.Filter(tt.items, WithPreReleases(tt.callPre)) + assert.Equal(t, tt.want, emptyToNil(got)) + }) + } +} + +func TestSpecifiers_Filter(t *testing.T) { + tests := []struct { + name string + spec string + specPre PreReleases + callPre PreReleases + items []string + want []string + }{ + // An empty set constrains nothing, so only the preference applies. + {"empty prefers final", "", PreReleasesAuto, PreReleasesAuto, + []string{"1.3", "1.5a1"}, []string{"1.3"}}, + {"empty offers lone pre", "", PreReleasesAuto, PreReleasesAuto, + []string{"1.5a1"}, []string{"1.5a1"}}, + {"empty include", "", PreReleasesInclude, PreReleasesAuto, + []string{"1.3", "1.5a1"}, []string{"1.3", "1.5a1"}}, + {"empty per-call include", "", PreReleasesAuto, PreReleasesInclude, + []string{"1.3", "1.5a1"}, []string{"1.3", "1.5a1"}}, + {"empty exclude", "", PreReleasesAuto, PreReleasesExclude, + []string{"1.3", "1.5a1"}, []string{"1.3"}}, + {"single spec prefers final", ">=1.2.3", PreReleasesAuto, PreReleasesAuto, + []string{"1.2", "1.3", "1.5a1"}, []string{"1.3"}}, + {"single spec offers lone pre", ">=1.2.3", PreReleasesAuto, PreReleasesAuto, + []string{"1.2", "1.5a1"}, []string{"1.5a1"}}, + // Two specifiers: the preference is decided over the versions that + // satisfied the WHOLE set, not per specifier. + {"conjunction prefers final", ">=1.0,<3", PreReleasesAuto, PreReleasesAuto, + []string{"1.0", "2.0a1"}, []string{"1.0"}}, + {"conjunction offers lone pre", ">=1.0,<3", PreReleasesAuto, PreReleasesAuto, + []string{"2.0a1"}, []string{"2.0a1"}}, + {"conjunction with pre operand", ">=1.0.dev1,<2", PreReleasesAuto, PreReleasesAuto, + []string{"1.0", "1.5a1"}, []string{"1.0", "1.5a1"}}, + {"arbitrary in a set", "===foobar", PreReleasesAuto, PreReleasesAuto, + []string{"foobar", "1.0"}, []string{"foobar"}}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + ss, err := NewSpecifiers(tt.spec, WithPreReleases(tt.specPre)) + require.NoError(t, err) + + got := ss.Filter(tt.items, WithPreReleases(tt.callPre)) + assert.Equal(t, tt.want, emptyToNil(got)) + }) + } +} + +// Filter must preserve input order, not the order the buffering logic happens +// to release items in. +func TestFilterPreservesInputOrder(t *testing.T) { + ss, err := NewSpecifiers(">=1.0", WithPreReleases(PreReleasesInclude)) + require.NoError(t, err) + items := []string{"3.0", "1.5a1", "2.0", "1.0"} + assert.Equal(t, items, ss.Filter(items)) +} + +// FilterBy is the `key=` seam: filtering a slice of arbitrary values by a +// version field. It must work for both Specifier and Specifiers. +func TestFilterBy(t *testing.T) { + type release struct { + name string + ver string + } + items := []release{{"a", "1.0"}, {"b", "2.1a1"}, {"c", "3.0"}} + key := func(r release) string { return r.ver } + + spec, err := NewSpecifier(">=2.0") + require.NoError(t, err) + assert.Equal(t, []release{{"c", "3.0"}}, FilterBy(spec, items, key)) + assert.Equal(t, + []release{{"b", "2.1a1"}, {"c", "3.0"}}, + FilterBy(spec, items, key, WithPreReleases(PreReleasesInclude))) + assert.Equal(t, []release{{"c", "3.0"}}, + FilterBy(spec, items, key, WithPreReleases(PreReleasesExclude))) + + // Only a pre-release matches: it is offered. + onlyPre := []release{{"b", "2.1a1"}} + assert.Equal(t, onlyPre, FilterBy(spec, onlyPre, key)) + assert.Empty(t, FilterBy(spec, onlyPre, key, WithPreReleases(PreReleasesExclude))) + + set, err := NewSpecifiers(">=2.0,<4") + require.NoError(t, err) + assert.Equal(t, []release{{"c", "3.0"}}, FilterBy(set, items, key)) + + // An empty set filters on the preference alone. + empty, err := NewSpecifiers("") + require.NoError(t, err) + assert.Equal(t, []release{{"a", "1.0"}, {"c", "3.0"}}, FilterBy(empty, items, key)) +} + +// ContainsVersion differs from Contains only for `===`, which compares the +// caller's spelling: a parsed Version has already been normalized, so +// `===1.1` contains Version("1.01") but not the string "1.01". +func TestArbitraryEqualityStringVersusVersion(t *testing.T) { + tests := []struct { + spec string + item string + wantStr bool + wantVers bool + }{ + {"===1.1", "1.01", false, true}, + {"===1.01", "1.01", true, false}, + {"===1.1", "1.1", true, true}, + {"===1.0", "01.0", false, true}, + {"===01.0", "01.0", true, false}, + {"===1.0", "0!1.0", false, true}, + {"===1.0.post1", "1.0-1", false, true}, + {"===1.0.dev1", "1.0.dev01", false, true}, + } + + for _, tt := range tests { + t.Run(tt.spec+"__"+tt.item, func(t *testing.T) { + s, err := NewSpecifier(tt.spec) + require.NoError(t, err) + assert.Equal(t, tt.wantStr, s.Contains(tt.item), "string operand") + + v, err := Parse(tt.item) + require.NoError(t, err) + assert.Equal(t, tt.wantVers, s.ContainsVersion(v), "Version operand") + }) + } +} + +// A non-PEP 440 string is reachable through Contains, which is what makes +// `===lolwat` testable end to end. Specifiers.Check cannot express this at +// all: version.Parse("lolwat") fails, so there is no Version to pass. +func TestArbitraryEqualityAcceptsNonVersionStrings(t *testing.T) { + tests := []struct { + spec string + item string + want bool + }{ + {"===lolwat", "lolwat", true}, + {"===lolwat", "LOLWAT", true}, + {"===LoLWaT", "lOlwAt", true}, + {"===lolwat", "notlolwat", false}, + {"===foobar", "invalid", false}, + {"===invalid", "invalid", true}, + // No other operator can match a non-version. + {"==1.0", "not a valid version", false}, + {">=1.0", "not a valid version", false}, + {"!=1.0", "not a valid version", false}, + {"~=1.0", "not a valid version", false}, + } + + for _, tt := range tests { + t.Run(tt.spec+"__"+tt.item, func(t *testing.T) { + s, err := NewSpecifier(tt.spec) + require.NoError(t, err) + assert.Equal(t, tt.want, s.Contains(tt.item)) + + ss, err := NewSpecifiers(tt.spec) + require.NoError(t, err) + assert.Equal(t, tt.want, ss.Contains(tt.item)) + }) + } +} + +// ContainsInstalled is upstream's installed=True carve-out: what is already on +// disk is recognized even when the set would not offer it as a new candidate. +func TestSpecifiers_ContainsInstalled(t *testing.T) { + tests := []struct { + spec string + item string + wantContains bool + wantInstalled bool + }{ + {">=1.0,<2", "1.5a1", false, true}, + {">=1.0", "2.0a1", false, true}, + {"<1.0", "0.9a1", false, true}, + // A final release is unaffected either way. + {"==1.0", "1.0", true, true}, + } + + for _, tt := range tests { + t.Run(tt.spec+"__"+tt.item, func(t *testing.T) { + ss, err := NewSpecifiers(tt.spec, WithPreReleases(PreReleasesExclude)) + require.NoError(t, err) + assert.Equal(t, tt.wantContains, ss.Contains(tt.item), "Contains") + assert.Equal(t, tt.wantInstalled, ss.ContainsInstalled(tt.item), "ContainsInstalled") + }) + } +} + +// Contains is defined as "Filter of one item is non-empty", exactly as +// upstream defines it, so the two can never disagree. Cross-check it. +func TestContainsAgreesWithFilterOfOne(t *testing.T) { + specs := []string{"", ">=1.0", "<2", "==2.0.*", "!=1.5", "~=1.4", ">=1.0.dev1", "===lolwat"} + items := []string{"1.0", "1.5", "2.0", "1.5a1", "2.0.dev1", "lolwat", "not a version"} + + for _, spec := range specs { + for _, policy := range []PreReleases{PreReleasesAuto, PreReleasesInclude, PreReleasesExclude} { + ss, err := NewSpecifiers(spec, WithPreReleases(policy)) + require.NoError(t, err) + for _, item := range items { + want := len(ss.Filter([]string{item})) > 0 + assert.Equal(t, want, ss.Contains(item), + "spec=%q policy=%s item=%q", spec, policy, item) + } + } + } +} + +func emptyToNil(s []string) []string { + if len(s) == 0 { + return nil + } + return s +} diff --git a/version/specifier.go b/version/specifier.go index d041253..a1ba81f 100644 --- a/version/specifier.go +++ b/version/specifier.go @@ -118,14 +118,34 @@ func init() { type operatorFunc func(v Version, c string) bool type Specifiers struct { - specifiers [][]specifier + specifiers [][]Specifier conf conf } -type specifier struct { - version string - operator operatorFunc +// Specifier is a single PEP 440 version specifier: one comparison operator +// and one operand, such as `>=1.2.3` or `===lolwat`. It is the unit +// pypa/packaging calls `Specifier`; the comma-separated set is Specifiers. +// +// The zero value is not a usable specifier. Build one with NewSpecifier, or +// read them off a Specifiers with Specifiers.List. +type Specifier struct { + // op is the comparison operator exactly as PEP 440 spells it ("==", + // "!=", "<", "<=", ">", ">=", "~=", "==="), or "" for the operator-less + // bare-version form this package deliberately admits (see the + // validConstraintRegexp comment in init). + op string + // operand is the right-hand side with surrounding whitespace removed and + // the sanitizer applied. It is NOT normalized as a version: upstream's + // Specifier.version returns the operand as written, so `==1.0A1` keeps + // its upper-case spelling. Verified against pypa/packaging 26.2. + operand string + // original is the specifier as matched in the input, whitespace and all. original string + // fn is the matching function for op. + fn operatorFunc + // pre is the pre-release policy this specifier was built with, before + // autodetection. PreReleasesAuto means "not set"; PreReleases resolves it. + pre PreReleases } // NewSpecifiersWithSanitizer parses a given specifier and returns a new instance of Specifiers @@ -154,30 +174,16 @@ func newRSpecifiers(v string, sanitizer func(string) string, opts ...SpecifierOp o.apply(c) } - var sss [][]specifier + var sss [][]Specifier for _, vv := range strings.Split(v, "||") { if strings.TrimSpace(vv) == "*" { vv = ">=0.0.0" } vv = strings.ReplaceAll(vv, "-", ".") - // Validate the segment - if !validConstraintRegexp.MatchString(vv) { - return Specifiers{}, fmt.Errorf("improper constraint: %s", vv) - } - - ss := specifierRegexp.FindAllString(vv, -1) - if ss == nil { - ss = append(ss, strings.TrimSpace(vv)) - } - - var specs []specifier - for _, single := range ss { - s, err := newSpecifier(single, sanitizer) - if err != nil { - return Specifiers{}, err - } - specs = append(specs, s) + specs, err := parseGroup(vv, sanitizer, *c) + if err != nil { + return Specifiers{}, err } sss = append(sss, specs) } @@ -198,29 +204,15 @@ func newSpecifiers(v string, sanitizer func(string) string, opts ...SpecifierOpt o.apply(c) } - var sss [][]specifier + var sss [][]Specifier for _, vv := range strings.Split(v, "||") { if strings.TrimSpace(vv) == "*" { vv = ">=0.0.0" } - // Validate the segment - if !validConstraintRegexp.MatchString(vv) { - return Specifiers{}, fmt.Errorf("improper constraint: %s", vv) - } - - ss := specifierRegexp.FindAllString(vv, -1) - if ss == nil { - ss = append(ss, strings.TrimSpace(vv)) - } - - var specs []specifier - for _, single := range ss { - s, err := newSpecifier(single, sanitizer) - if err != nil { - return Specifiers{}, err - } - specs = append(specs, s) + specs, err := parseGroup(vv, sanitizer, *c) + if err != nil { + return Specifiers{}, err } sss = append(sss, specs) } @@ -232,10 +224,69 @@ func newSpecifiers(v string, sanitizer func(string) string, opts ...SpecifierOpt } -func newSpecifier(s string, sanitizer func(s string) string) (specifier, error) { +// NewSpecifier parses a single PEP 440 version specifier, such as `>=1.2.3`. +// +// It is the singular counterpart to NewSpecifiers and mirrors upstream's +// `Specifier(spec, prereleases=...)` constructor. A comma-separated set is not +// a single specifier: pass those to NewSpecifiers instead. +func NewSpecifier(s string, opts ...SpecifierOption) (Specifier, error) { + c := new(conf) + for _, o := range opts { + o.apply(c) + } + + // Reject anything the specifier grammar does not accept in full, so that + // NewSpecifier(">=1,<2") is an error rather than a silent ">=1" with the + // rest dropped on the floor. specifierRegexp is unanchored (Specifiers + // scans with it), so a bare FindStringSubmatch would happily match a + // prefix. + if !validConstraintRegexp.MatchString(s) { + return Specifier{}, fmt.Errorf("improper specifier: %s", s) + } + found := specifierRegexp.FindAllString(s, -1) + if len(found) != 1 { + return Specifier{}, fmt.Errorf("improper specifier: %s", s) + } + + return newSpecifier(found[0], func(v string) string { return v }, *c) +} + +// parseGroup parses one AND-group: a comma-separated run of specifiers. +// +// An empty group is legal and yields zero specifiers, which is how +// `NewSpecifiers("")` becomes the universal set rather than an error. Upstream +// reaches the same place from the other end, by dropping empty items after +// splitting on the comma (`[s.strip() for s in specifiers.split(",") if +// s.strip()]`), which is also why it accepts a leading or doubled comma. +func parseGroup(vv string, sanitizer func(string) string, c conf) ([]Specifier, error) { + if !validConstraintRegexp.MatchString(vv) { + return nil, fmt.Errorf("improper constraint: %s", vv) + } + + found := specifierRegexp.FindAllString(vv, -1) + if found == nil { + if strings.TrimSpace(vv) == "" { + // The universal set. Not an error, and NOT a floor of zero. + return nil, nil + } + found = append(found, strings.TrimSpace(vv)) + } + + specs := make([]Specifier, 0, len(found)) + for _, single := range found { + s, err := newSpecifier(single, sanitizer, c) + if err != nil { + return nil, err + } + specs = append(specs, s) + } + return specs, nil +} + +func newSpecifier(s string, sanitizer func(s string) string, c conf) (Specifier, error) { m := specifierRegexp.FindStringSubmatch(s) if m == nil { - return specifier{}, fmt.Errorf("improper specifier: %s", s) + return Specifier{}, fmt.Errorf("improper specifier: %s", s) } operator := m[specifierRegexp.SubexpIndex("operator")] @@ -250,14 +301,16 @@ func newSpecifier(s string, sanitizer func(s string) string) (specifier, error) if operator != "===" { if err := validate(operator, version); err != nil { - return specifier{}, err + return Specifier{}, err } } - return specifier{ - version: version, - operator: specifierOperators[operator], + return Specifier{ + op: operator, + operand: version, original: s, + fn: specifierOperators[operator], + pre: c.preReleases, }, nil } @@ -314,11 +367,10 @@ func validate(operator, version string) error { // Note that andCheck below already returns true for an empty AND-group, for the // same reason: a conjunction over no constraints is vacuously true. Zero // OR-groups is the same statement one level up, and the two must agree. +// Check is pure MATCHING: it ignores the pre-release policy entirely and asks +// only whether v satisfies the operators. Use Contains for the PEP 440 +// selection semantics, where the policy applies. func (ss Specifiers) Check(v Version) bool { - if ss.conf.includePreRelease { - v.preReleaseIncluded = true - } - if len(ss.specifiers) == 0 { return true } @@ -332,15 +384,53 @@ func (ss Specifiers) Check(v Version) bool { return false } -func (s specifier) check(v Version) bool { - return s.operator(v, s.version) +// Check reports whether v satisfies this single specifier's operator. Like +// Specifiers.Check it is pure matching, with no pre-release selection. +func (s Specifier) Check(v Version) bool { + if s.fn == nil { + // A zero-value Specifier constrains nothing, for the same reason an + // empty Specifiers admits every version. + return true + } + return s.fn(v, s.operand) } -func (s specifier) String() string { - return s.original +// Operator returns the comparison operator as PEP 440 spells it: "==", "!=", +// "<", "<=", ">", ">=", "~=" or "===". +// +// It returns "" for the operator-less bare-version form, which PEP 440 does +// not define and upstream rejects; this package admits it deliberately for the +// R constraint path (see the validConstraintRegexp comment in init). +func (s Specifier) Operator() string { return s.op } + +// Version returns the specifier's operand as written, with surrounding +// whitespace removed: `Specifier("== 1.0A1").Version()` is "1.0A1", not +// "1.0a1". Upstream does the same — the operand is normalized when it is +// compared, not when it is stored. +func (s Specifier) Version() string { return s.operand } + +// Original returns the specifier exactly as it appeared in the input, +// whitespace included. +func (s Specifier) Original() string { return s.original } + +// String returns the normalized form: the operator immediately followed by the +// operand, with the whitespace PEP 440 permits between them removed. So +// `NewSpecifier("< 2").String()` is "<2", matching upstream's `str()`. +func (s Specifier) String() string { + return s.op + s.operand } -// String returns the string format of the specifiers +// String returns the string format of the specifiers. +// +// Each specifier is rendered normalized (see Specifier.String), so +// `NewSpecifiers("< 2").String()` is "<2". +// +// ⚠️ Input order is preserved. Upstream's SpecifierSet.__str__ sorts its +// members, so `SpecifierSet(">=1,<2")` renders as "<2,>=1"; this package +// renders ">=1,<2". That divergence is deliberate and left in place: the +// OR-of-ANDs shape this type carries for the R path (`a || b`) has no upstream +// counterpart to sort within, and reordering would churn Requirement.String +// for no conformance gain. func (ss Specifiers) String() string { var ssStr []string for _, orS := range ss.specifiers { @@ -354,9 +444,31 @@ func (ss Specifiers) String() string { return strings.Join(ssStr, "||") } -func andCheck(v Version, specifiers []specifier) bool { +// Len returns the number of specifiers in the set, matching upstream's +// `len(SpecifierSet)`. For a set carrying more than one OR-group (the R-only +// `||` syntax, which upstream has no equivalent for) it is the total across +// every group. +func (ss Specifiers) Len() int { + n := 0 + for _, group := range ss.specifiers { + n += len(group) + } + return n +} + +// List returns the individual specifiers, flattened across OR-groups in input +// order. It is the iteration upstream gets from `iter(SpecifierSet)`. +func (ss Specifiers) List() []Specifier { + out := make([]Specifier, 0, ss.Len()) + for _, group := range ss.specifiers { + out = append(out, group...) + } + return out +} + +func andCheck(v Version, specifiers []Specifier) bool { for _, c := range specifiers { - if !c.check(v) { + if !c.Check(v) { return false } } @@ -415,6 +527,31 @@ func padVersion(left, right []string) ([]string, []string) { // Specifier functions //------------------------------------------------------------------- +// parseOperand parses a matching operand, reporting failure instead of +// panicking. +// +// The comparison functions below used to call MustParse at six sites. Every +// one of them was, at the time, only reachable with an operand the specifier +// grammar had already validated, so none could actually panic through the +// public API — but "unreachable" was a property of the CALLERS, not of these +// functions, and it stopped being true the moment a new caller appeared. The +// exported Specifier type is exactly that new caller: it can be built inside +// this package with any operand at all, and Filter drives these functions +// directly. A panic on the matching path of a library that parses +// remote-supplied requirement strings is not a landmine worth keeping for the +// sake of two fewer lines. +// +// A failed parse means "this comparison cannot be made", which yields no +// match. It cannot mean "match", because that would admit versions on the +// strength of an operand nobody could interpret. +func parseOperand(s string) (Version, bool) { + v, err := Parse(s) + if err != nil { + return Version{}, false + } + return v, true +} + func specifierCompatible(prospective Version, spec string) bool { // Compatible releases have an equivalent combination of >= and ==. That is that ~=2.2 is equivalent to >=2.2,==2.*. // This allows us to implement this in terms of the other specifiers instead of implementing it ourselves. @@ -443,7 +580,11 @@ func specifierEqual(prospective Version, spec string) bool { // We need special logic to handle prefix matching if strings.HasSuffix(spec, ".*") { // In the case of prefix matching we want to ignore local segment. - prospective = MustParse(prospective.Public()) + public, ok := parseOperand(prospective.Public()) + if !ok { + return false + } + prospective = public // Split the spec out by dots, and pretend that there is an implicit // dot in between a release segment and a pre-release segment. @@ -464,9 +605,16 @@ func specifierEqual(prospective Version, spec string) bool { return reflect.DeepEqual(paddedSpec, paddedProspective) } - specVersion := MustParse(spec) + specVersion, ok := parseOperand(spec) + if !ok { + return false + } if specVersion.local == "" { - prospective = MustParse(prospective.Public()) + public, ok := parseOperand(prospective.Public()) + if !ok { + return false + } + prospective = public } return specVersion.Equal(prospective) @@ -478,7 +626,10 @@ func specifierNotEqual(prospective Version, spec string) bool { func specifierLessThan(prospective Version, spec string) bool { // Convert our spec to a Version instance, since we'll want to work with it as a version. - s := MustParse(spec) + s, ok := parseOperand(spec) + if !ok { + return false + } // Check to see if the prospective version is less than the spec version. // If it's not we can short circuit and just return False now instead of doing extra unneeded work. @@ -489,17 +640,38 @@ func specifierLessThan(prospective Version, spec string) bool { // This special case is here so that, unless the specifier itself includes is a pre-release version, // that we do not accept pre-release versions for the version mentioned in the specifier // (e.g. <3.1 should not match 3.1.dev0, but should match 3.0.dev0). + // + // ⚠️ This guard is MATCHING, not candidate selection: no pre-release + // policy turns it off. `<3.1` does not contain `3.1.dev0` even with + // PreReleasesInclude, which is what pypa/packaging 26.2 does. if !s.IsPreRelease() && prospective.IsPreRelease() { - if MustParse(prospective.BaseVersion()).Equal(MustParse(s.BaseVersion())) { + if sameBaseVersion(prospective, s) { return false } } return true } +// sameBaseVersion reports whether two versions share a base version (release +// segment and epoch, with pre/post/dev/local discarded). +func sameBaseVersion(a, b Version) bool { + av, ok := parseOperand(a.BaseVersion()) + if !ok { + return false + } + bv, ok := parseOperand(b.BaseVersion()) + if !ok { + return false + } + return av.Equal(bv) +} + func specifierGreaterThan(prospective Version, spec string) bool { // Convert our spec to a Version instance, since we'll want to work with it as a version. - s := MustParse(spec) + s, ok := parseOperand(spec) + if !ok { + return false + } // Check to see if the prospective version is greater than the spec version. // If it's not we can short circuit and just return False now instead of doing extra unneeded work. @@ -510,8 +682,10 @@ func specifierGreaterThan(prospective Version, spec string) bool { // This special case is here so that, unless the specifier itself includes is a post-release version, // that we do not accept post-release versions for the version mentioned in the specifier // (e.g. >3.1 should not match 3.0.post0, but should match 3.2.post0). + // + // ⚠️ Matching, not candidate selection. See specifierLessThan. if !s.IsPostRelease() && prospective.IsPostRelease() { - if MustParse(prospective.BaseVersion()).Equal(MustParse(s.BaseVersion())) { + if sameBaseVersion(prospective, s) { return false } } @@ -519,7 +693,7 @@ func specifierGreaterThan(prospective Version, spec string) bool { // Ensure that we do not allow a local version of the version mentioned // in the specifier, which is technically greater than, to match. if prospective.local != "" { - if MustParse(prospective.BaseVersion()).Equal(MustParse(s.BaseVersion())) { + if sameBaseVersion(prospective, s) { return false } } @@ -531,13 +705,19 @@ func specifierArbitrary(prospective Version, spec string) bool { } func specifierLessThanEqual(prospective Version, spec string) bool { - p := MustParse(prospective.Public()) - s := MustParse(spec) + p, pok := parseOperand(prospective.Public()) + s, sok := parseOperand(spec) + if !pok || !sok { + return false + } return p.LessThanOrEqual(s) } func specifierGreaterThanEqual(prospective Version, spec string) bool { - p := MustParse(prospective.Public()) - s := MustParse(spec) + p, pok := parseOperand(prospective.Public()) + s, sok := parseOperand(spec) + if !pok || !sok { + return false + } return p.GreaterThanOrEqual(s) } diff --git a/version/specifier_api_test.go b/version/specifier_api_test.go new file mode 100644 index 0000000..7bed143 --- /dev/null +++ b/version/specifier_api_test.go @@ -0,0 +1,343 @@ +// SPDX-License-Identifier: Apache-2.0 OR MIT + +// Unit tests for the public specifier API added for +// rstudio/package-manager#19383: the singular Specifier, its accessors and +// canonical equality, set length/iteration/combination, and the empty set. +// +// Every expected value in this file was measured against pypa/packaging 26.2, +// not derived from the PEP text. The conformance tables ported from upstream's +// own test suite live separately, in specifier_conformance_test.go. + +package version + +import ( + "fmt" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestNewSpecifier_Accessors(t *testing.T) { + tests := []struct { + in string + op string + operand string + str string + }{ + {"~=2.0", "~=", "2.0", "~=2.0"}, + {"==2.1.*", "==", "2.1.*", "==2.1.*"}, + {"==2.1.0.3", "==", "2.1.0.3", "==2.1.0.3"}, + {"!=2.2.*", "!=", "2.2.*", "!=2.2.*"}, + {"<=5", "<=", "5", "<=5"}, + {">=7.9a1", ">=", "7.9a1", ">=7.9a1"}, + {"<1.0.dev1", "<", "1.0.dev1", "<1.0.dev1"}, + {">2.0.post1", ">", "2.0.post1", ">2.0.post1"}, + // === is PEP 440's escape hatch: the operand is an opaque token. + {"===lolwat", "===", "lolwat", "===lolwat"}, + // Whitespace between operator and operand is removed by String, which + // is the whole of upstream's normalization at this level. + {"< 2", "<", "2", "<2"}, + // ⚠️ The operand is NOT normalized as a version. Upstream's + // Specifier.version returns it as written, so the "v" prefix survives: + // Specifier(">= v1.0 ").version -> 'v1.0' + // + // The upper-case counterpart ("== 1.0A1" -> '1.0A1') is a separate, + // still-open divergence: validConstraintRegexp lacks the (?i) flag + // specifierRegexp has, so an upper-case operand is rejected before it + // reaches this code. Tracked with the other parse divergences in + // rstudio/package-manager#19391. + {">= v1.0 ", ">=", "v1.0", ">=v1.0"}, + } + + for _, tt := range tests { + t.Run(tt.in, func(t *testing.T) { + s, err := NewSpecifier(tt.in) + require.NoError(t, err) + assert.Equal(t, tt.op, s.Operator(), "Operator()") + assert.Equal(t, tt.operand, s.Version(), "Version()") + assert.Equal(t, tt.str, s.String(), "String()") + }) + } +} + +// NewSpecifier is the SINGULAR constructor. A comma-separated set is not one +// specifier, and must not quietly parse as its first member with the rest +// discarded -- the failure mode would be a constraint that matches far more +// than the caller wrote. +func TestNewSpecifier_RejectsASet(t *testing.T) { + for _, in := range []string{">=1,<2", "==1.0,==2.0", ">=1.0 <2.0"} { + t.Run(in, func(t *testing.T) { + _, err := NewSpecifier(in) + assert.Error(t, err) + }) + } +} + +func TestNewSpecifier_Invalid(t *testing.T) { + for _, in := range []string{"", "=>2.0", "==", "~=1", ">=1.0+deadbeef", "<1.0.*"} { + t.Run(fmt.Sprintf("%q", in), func(t *testing.T) { + _, err := NewSpecifier(in) + assert.Error(t, err) + }) + } +} + +// Specifier.Equal canonicalizes the operand rather than comparing text, so +// trailing zeros, case, a "v" prefix, a zero epoch and local-segment case are +// all insignificant -- except under "~=", where trailing zeros change which +// versions match and so must stay significant. +func TestSpecifier_Equal_Canonicalizes(t *testing.T) { + tests := []struct { + left, right string + want bool + }{ + {"==2.8.0", "==2.8", true}, + {"==1.0.0.0", "==1", true}, + {"< 2", "<2", true}, + {"==1.01", "==1.1", true}, + {"==v1.0", "==1.0", true}, + {"==0!1.0", "==1.0", true}, + // The case-insensitive pairs upstream also treats as equal + // (`==1.0A1`/`==1.0a1`, `==1.0+abc`/`==1.0+ABC`) cannot be built yet: + // validConstraintRegexp rejects an upper-case operand. See + // rstudio/package-manager#19391. + {"==2.1.*", "==2.1.*", true}, + {"~=1.2.0", "~=1.2.0", true}, + // ⚠️ `~=1.18` and `~=1.18.0` accept different sets, so the trailing + // zero is load-bearing and they are NOT equal. Upstream keeps trailing + // zeros for `~=` alone (strip_trailing_zero=(operator != "~=")). + {"~=1.18.0", "~=1.18", false}, + {"==1.0", "!=1.0", false}, + // A wildcard operand is compared verbatim: it is not a version, so + // there is nothing to canonicalize, and "2.1.*" and "2.1.0.*" are + // genuinely different prefixes. + {"==2.1.*", "==2.1.0.*", false}, + // An arbitrary-equality operand is likewise verbatim, case included. + {"===lolwat", "===LOLWAT", false}, + } + + for _, tt := range tests { + t.Run(tt.left+"__"+tt.right, func(t *testing.T) { + l, err := NewSpecifier(tt.left) + require.NoError(t, err) + r, err := NewSpecifier(tt.right) + require.NoError(t, err) + assert.Equal(t, tt.want, l.Equal(r)) + assert.Equal(t, tt.want, r.Equal(l), "Equal must be symmetric") + }) + } +} + +// A pre-release policy is explicitly NOT part of equality: two specifiers that +// differ only in policy are the same constraint. +func TestSpecifier_Equal_IgnoresPreReleasePolicy(t *testing.T) { + a, err := NewSpecifier(">=1.2.3", WithPreReleases(PreReleasesInclude)) + require.NoError(t, err) + b, err := NewSpecifier(">=1.2.3", WithPreReleases(PreReleasesExclude)) + require.NoError(t, err) + assert.True(t, a.Equal(b)) +} + +func TestSpecifiers_LenAndList(t *testing.T) { + tests := []struct { + in string + len int + items []string + }{ + {"", 0, nil}, + {"==2.0", 1, []string{"==2.0"}}, + {">=2.0", 1, []string{">=2.0"}}, + {">=2.0,<3", 2, []string{">=2.0", "<3"}}, + {">=2.0,<3,==2.4", 3, []string{">=2.0", "<3", "==2.4"}}, + } + + for _, tt := range tests { + t.Run(fmt.Sprintf("%q", tt.in), func(t *testing.T) { + ss, err := NewSpecifiers(tt.in) + require.NoError(t, err) + assert.Equal(t, tt.len, ss.Len()) + + var got []string + for _, s := range ss.List() { + got = append(got, s.String()) + } + assert.ElementsMatch(t, tt.items, got) + assert.Len(t, ss.List(), ss.Len(), "List and Len must agree") + }) + } +} + +// NewSpecifiers("") is the universal set, not an error and not an empty one. +// Upstream's SpecifierSet(”) has length zero and contains every version; this +// package used to reject the empty string outright (the residue noted on +// rstudio/package-manager#19391 after #19366/#19465 fixed the zero-value arm). +func TestNewSpecifiers_EmptyStringIsUniversal(t *testing.T) { + ss, err := NewSpecifiers("") + require.NoError(t, err) + assert.Equal(t, 0, ss.Len()) + assert.Equal(t, "", ss.String()) + + for _, v := range []string{"0", "1.0", "2.0a1", "1!3.0", "1.0.dev0", "1.0+local"} { + assert.True(t, ss.Check(MustParse(v)), "Check(%s)", v) + } +} + +func TestSpecifiers_And(t *testing.T) { + left, err := NewSpecifiers(">=1.0.0,!=1.0.1") + require.NoError(t, err) + right, err := NewSpecifiers("<=2.0.0,!=2.0.1") + require.NoError(t, err) + + combined, err := left.And(right) + require.NoError(t, err) + assert.Equal(t, 4, combined.Len()) + + // The intersection must actually intersect. + assert.True(t, combined.Check(MustParse("1.5"))) + assert.False(t, combined.Check(MustParse("1.0.1"))) + assert.False(t, combined.Check(MustParse("2.0.1"))) + assert.False(t, combined.Check(MustParse("3.0"))) +} + +// ⚠️ And keeps duplicates rather than deduplicating, matching upstream: +// len(SpecifierSet(">=1.0") & SpecifierSet(">=1.0")) is 2 in packaging 26.2, +// even though its str() renders the deduplicated ">=1.0". Equal is the +// operation that is blind to duplicates. +func TestSpecifiers_And_KeepsDuplicatesButEqualIgnoresThem(t *testing.T) { + one, err := NewSpecifiers(">=1.0") + require.NoError(t, err) + + combined, err := one.And(one) + require.NoError(t, err) + assert.Equal(t, 2, combined.Len()) + assert.True(t, combined.Equal(one)) +} + +func TestSpecifiers_And_PreReleasePolicyCombination(t *testing.T) { + tests := []struct { + left, right PreReleases + want PreReleases + wantErr bool + }{ + {PreReleasesAuto, PreReleasesAuto, PreReleasesAuto, false}, + {PreReleasesAuto, PreReleasesInclude, PreReleasesInclude, false}, + {PreReleasesAuto, PreReleasesExclude, PreReleasesExclude, false}, + {PreReleasesInclude, PreReleasesAuto, PreReleasesInclude, false}, + {PreReleasesInclude, PreReleasesInclude, PreReleasesInclude, false}, + {PreReleasesExclude, PreReleasesAuto, PreReleasesExclude, false}, + {PreReleasesExclude, PreReleasesExclude, PreReleasesExclude, false}, + // A contradiction is an error, not a silent winner. + {PreReleasesInclude, PreReleasesExclude, PreReleasesAuto, true}, + {PreReleasesExclude, PreReleasesInclude, PreReleasesAuto, true}, + } + + for _, tt := range tests { + t.Run(tt.left.String()+"__"+tt.right.String(), func(t *testing.T) { + l, err := NewSpecifiers(">=1", WithPreReleases(tt.left)) + require.NoError(t, err) + r, err := NewSpecifiers("<2", WithPreReleases(tt.right)) + require.NoError(t, err) + + combined, err := l.And(r) + if tt.wantErr { + assert.ErrorIs(t, err, ErrPreReleaseConflict) + return + } + require.NoError(t, err) + assert.Equal(t, tt.want, combined.PreReleases()) + }) + } +} + +func TestSpecifiers_Equal_IgnoresOrderAndDuplicates(t *testing.T) { + tests := []struct { + left, right string + want bool + }{ + {">=1,<2", "<2,>=1", true}, + {">=1,>=1", ">=1", true}, + {">=1.0.0", ">=1", true}, + {">=1,<2", ">=1", false}, + {">=1,<2", ">=1,<3", false}, + } + + for _, tt := range tests { + t.Run(tt.left+"__"+tt.right, func(t *testing.T) { + l, err := NewSpecifiers(tt.left) + require.NoError(t, err) + r, err := NewSpecifiers(tt.right) + require.NoError(t, err) + assert.Equal(t, tt.want, l.Equal(r)) + assert.Equal(t, tt.want, r.Equal(l)) + }) + } +} + +func TestNewSpecifiersFrom(t *testing.T) { + lower, err := NewSpecifier(">=1.0") + require.NoError(t, err) + upper, err := NewSpecifier("<2.0") + require.NoError(t, err) + + ss := NewSpecifiersFrom([]Specifier{lower, upper}) + assert.Equal(t, 2, ss.Len()) + assert.Equal(t, ">=1.0,<2.0", ss.String()) + assert.True(t, ss.Check(MustParse("1.5"))) + assert.False(t, ss.Check(MustParse("2.5"))) + + parsed, err := NewSpecifiers(">=1.0,<2.0") + require.NoError(t, err) + assert.True(t, ss.Equal(parsed)) +} + +// NewSpecifiersFrom must copy: mutating the caller's slice afterwards cannot +// be allowed to change the set. +func TestNewSpecifiersFrom_CopiesInput(t *testing.T) { + lower, err := NewSpecifier(">=1.0") + require.NoError(t, err) + other, err := NewSpecifier("==9.9") + require.NoError(t, err) + + input := []Specifier{lower} + ss := NewSpecifiersFrom(input) + input[0] = other + + assert.Equal(t, ">=1.0", ss.String()) +} + +// Specifiers.String renders each member normalized. Before this change it +// returned the raw input text, so "< 2" round-tripped as "< 2" while upstream +// gives "<2". +func TestSpecifiers_String_IsNormalized(t *testing.T) { + tests := []struct { + in string + want string + }{ + {"< 2", "<2"}, + {"== 1.0", "==1.0"}, + {">= v1.0 ", ">=v1.0"}, + {">= 1.0, < 2.0", ">=1.0,<2.0"}, + {"==2.0", "==2.0"}, + } + for _, tt := range tests { + t.Run(tt.in, func(t *testing.T) { + ss, err := NewSpecifiers(tt.in) + require.NoError(t, err) + assert.Equal(t, tt.want, ss.String()) + }) + } +} + +// A zero-value Specifier has no operator function. It must constrain nothing +// rather than panic on a nil call -- the same reading that makes an empty +// Specifiers universal (rstudio/package-manager#19366). +func TestZeroValueSpecifierIsHarmless(t *testing.T) { + var s Specifier + assert.Equal(t, "", s.Operator()) + assert.Equal(t, "", s.Version()) + assert.Equal(t, "", s.String()) + assert.NotPanics(t, func() { + assert.True(t, s.Check(MustParse("1.0"))) + }) +} diff --git a/version/specifier_option.go b/version/specifier_option.go index 0207768..aae53ec 100644 --- a/version/specifier_option.go +++ b/version/specifier_option.go @@ -3,15 +3,33 @@ package version type conf struct { - includePreRelease bool + preReleases PreReleases } type SpecifierOption interface { apply(*conf) } +// WithPreRelease is the original two-state pre-release switch. +// +// Deprecated: use WithPreReleases, which can express all three PEP 440 states. +// WithPreRelease(true) maps to PreReleasesInclude and WithPreRelease(false) to +// PreReleasesAuto — false has never meant "exclude" here, it meant "no +// override", which is what PreReleasesAuto spells out. +// +// ⚠️ WithPreRelease(true) also used to suppress the operator-level pre-release +// guards, by setting a flag that made Version.IsPreRelease report false for a +// version that plainly is one. That conflated candidate SELECTION with +// MATCHING: it made `<2` match `2.0.dev1`, which pypa/packaging 26.2 rejects +// with `prereleases=True` just as it does without it (verified against the +// reference implementation). The flag is gone, so `<2` no longer matches +// `2.0.dev1` under this option. See the PreReleases doc comment. type WithPreRelease bool func (o WithPreRelease) apply(c *conf) { - c.includePreRelease = bool(o) + if bool(o) { + c.preReleases = PreReleasesInclude + return + } + c.preReleases = PreReleasesAuto } diff --git a/version/specifier_query.go b/version/specifier_query.go new file mode 100644 index 0000000..a4a2d21 --- /dev/null +++ b/version/specifier_query.go @@ -0,0 +1,569 @@ +// SPDX-License-Identifier: Apache-2.0 OR MIT + +// This file holds the query half of the specifier API — the pre-release-aware +// Contains and Filter methods, the resolved PreReleases policy, canonical +// equality, and set combination. It follows the structure of +// pypa/packaging's specifiers.py, where `contains` is defined as +// `bool(list(self.filter([item])))` so the two can never disagree. +// +// Upstream pinned at 4eb0753dba8fcaaac8eb75463374e448f0931558 +// (pypa/packaging 26.2). + +package version + +import ( + "errors" + "strings" +) + +// ErrPreReleaseConflict is returned by Specifiers.And when the two sets carry +// contradictory explicit pre-release policies (one Include, one Exclude). +// Upstream raises ValueError in the same case; PreReleasesAuto on either side +// yields to the other. +var ErrPreReleaseConflict = errors.New("cannot combine specifier sets with conflicting explicit pre-release policies") + +//------------------------------------------------------------------- +// Resolved pre-release policy +//------------------------------------------------------------------- + +// PreReleases returns the pre-release policy in force for this specifier: the +// policy it was built with, or, for PreReleasesAuto, the one PEP 440 derives +// from the specifier itself. +// +// The derivation matches upstream's Specifier.prereleases property exactly: +// +// - `!=` never implies pre-releases, even against a pre-release operand. +// - `==` with a `.*` wildcard never implies pre-releases. +// - `===` cannot be parsed as a version at all, so the policy stays +// unresolved (upstream's `None`, PreReleasesAuto here). +// - otherwise, the policy is Include exactly when the operand is itself a +// pre-release, so `>=1.0.dev1` offers pre-releases and `>=1.0` does not. +func (s Specifier) PreReleases() PreReleases { + if s.pre != PreReleasesAuto { + return s.pre + } + + switch { + case s.op == "!=": + return PreReleasesExclude + case s.op == "==" && strings.HasSuffix(s.operand, ".*"): + return PreReleasesExclude + } + + // `===` gets no special case: upstream tries to parse its operand like any + // other and only falls through to "unresolved" when that fails. So + // `===lolwat` is unresolved but `===1.0.dev1` resolves to Include, because + // its operand does happen to be a pre-release version. + v, err := Parse(s.operand) + if err != nil { + return PreReleasesAuto + } + if v.IsPreRelease() { + return PreReleasesInclude + } + return PreReleasesExclude +} + +// PreReleases returns the pre-release policy in force for the set: the policy +// it was built with, or, for PreReleasesAuto, Include when any member +// specifier resolves to Include and PreReleasesAuto otherwise. +// +// ⚠️ Note the asymmetry with Specifier.PreReleases, which is upstream's and +// not an oversight: a set of ordinary final-release specifiers resolves to +// PreReleasesAuto (`None`), never to Exclude, even though each member on its +// own resolves to Exclude. That is what lets a set fall back to offering +// pre-releases when nothing else matched, while a single specifier queried +// directly does not. +func (ss Specifiers) PreReleases() PreReleases { + if ss.conf.preReleases != PreReleasesAuto { + return ss.conf.preReleases + } + if ss.Len() == 0 { + return PreReleasesAuto + } + for _, s := range ss.List() { + if s.PreReleases() == PreReleasesInclude { + return PreReleasesInclude + } + } + return PreReleasesAuto +} + +//------------------------------------------------------------------- +// Specifier: Contains / Filter +//------------------------------------------------------------------- + +// Contains reports whether item satisfies this specifier under the PEP 440 +// pre-release selection rules. +// +// item is a raw string, and that matters for `===`: arbitrary equality +// compares the operand against the string as written, so `===1.01` contains +// the string "1.01" but not the string "1.1". Pass a parsed Version to +// ContainsVersion for the normalized comparison instead. +// +// A string that is not a valid PEP 440 version is not an error: it simply +// cannot match anything except a `===` operand spelled the same way. +// +// ⚠️ A pre-release DOES satisfy an ordinary specifier when queried on its own. +// Contains(">=1.0", "1.5a1") is true, because with one candidate under +// consideration there is no final release to prefer. See the PreReleases doc +// comment. +func (s Specifier) Contains(item string, opts ...FilterOption) bool { + return len(s.Filter([]string{item}, opts...)) > 0 +} + +// ContainsVersion is Contains for an already-parsed Version. The only +// observable difference is for `===`, which compares against v's normalized +// rendering rather than the caller's original spelling. +func (s Specifier) ContainsVersion(v Version, opts ...FilterOption) bool { + return len(s.FilterVersions([]Version{v}, opts...)) > 0 +} + +// Filter returns the members of items this specifier offers as candidates, +// preserving input order. +// +// The PEP 440 rule is a preference, not a hard exclusion: pre-releases are +// held back while any final release matches, and offered when none does. +// +// Filter(">=1.2.3", ["1.2", "1.3", "1.5a1"]) -> ["1.3"] +// Filter(">=1.2.3", ["1.2", "1.5a1"]) -> ["1.5a1"] +// +// Pass WithPreReleases to override the policy for this call only. +func (s Specifier) Filter(items []string, opts ...FilterOption) []string { + return filterGeneric(s, items, func(v string) string { return v }, opts) +} + +// FilterVersions is Filter over already-parsed versions. +func (s Specifier) FilterVersions(items []Version, opts ...FilterOption) []Version { + return filterGeneric(s, items, Version.String, opts) +} + +// Equal reports whether two specifiers are equal after canonicalization, +// matching upstream's Specifier.__eq__. The pre-release policy is ignored, +// trailing zeros in the operand are not significant, and the operand's case +// and `v` prefix are normalized: +// +// ==2.8.0 == ==2.8 (true) +// ==1.0A1 == ==1.0a1 (true) +// ~=1.18.0 == ~=1.18 (FALSE — `~=` keeps trailing zeros, because they +// change which versions it matches) +// +// A `===` operand and a `.*` wildcard are compared verbatim, since neither is +// a version that can be canonicalized. +func (s Specifier) Equal(other Specifier) bool { + lop, lv := s.canonicalSpec() + rop, rv := other.canonicalSpec() + return lop == rop && lv == rv +} + +// canonicalSpec is upstream's Specifier._canonical_spec. +func (s Specifier) canonicalSpec() (op, operand string) { + if s.op == "===" || strings.HasSuffix(s.operand, ".*") { + return s.op, s.operand + } + v, err := Parse(s.operand) + if err != nil { + // Unreachable for a specifier built by this package: every operand + // except `===` is validated at construction. Degrade to the raw text + // rather than panicking on a zero value. + return s.op, s.operand + } + if s.op == "~=" { + // Trailing zeros are load-bearing for the compatible operator: + // `~=1.18` and `~=1.18.0` accept different version sets. + return s.op, v.String() + } + return s.op, v.trimmedRelease() +} + +//------------------------------------------------------------------- +// Specifiers: Contains / Filter / And +//------------------------------------------------------------------- + +// Contains reports whether item satisfies every specifier in the set, under +// the PEP 440 pre-release selection rules. See Specifier.Contains for how a +// raw string interacts with `===`. +// +// An empty set contains every version, pre-releases included. +func (ss Specifiers) Contains(item string, opts ...FilterOption) bool { + return len(ss.Filter([]string{item}, opts...)) > 0 +} + +// ContainsVersion is Contains for an already-parsed Version. +func (ss Specifiers) ContainsVersion(v Version, opts ...FilterOption) bool { + return len(ss.FilterVersions([]Version{v}, opts...)) > 0 +} + +// ContainsInstalled is Contains with upstream's `installed=True` carve-out: an +// already-installed pre-release is accepted even when the set would not offer +// it as a new candidate, because refusing to recognize what is on disk is not +// useful. It has no effect on a version that is not a pre-release. +func (ss Specifiers) ContainsInstalled(item string, opts ...FilterOption) bool { + if v, err := Parse(item); err == nil && v.IsPreRelease() { + opts = append(opts, WithPreReleases(PreReleasesInclude)) + } + return ss.Contains(item, opts...) +} + +// Filter returns the members of items the set offers as candidates, +// preserving input order. See Specifier.Filter for the pre-release rule. +func (ss Specifiers) Filter(items []string, opts ...FilterOption) []string { + return filterGeneric(ss, items, func(v string) string { return v }, opts) +} + +// FilterVersions is Filter over already-parsed versions. +func (ss Specifiers) FilterVersions(items []Version, opts ...FilterOption) []Version { + return filterGeneric(ss, items, Version.String, opts) +} + +// Equal reports whether two sets hold the same specifiers, compared +// canonically and irrespective of order, duplicates, or pre-release policy. +// It is upstream's SpecifierSet.__eq__. +func (ss Specifiers) Equal(other Specifiers) bool { + left := canonicalKeys(ss) + right := canonicalKeys(other) + if len(left) != len(right) { + return false + } + for k := range left { + if _, ok := right[k]; !ok { + return false + } + } + return true +} + +// canonicalKeys is the deduplicated set of canonical specifier renderings, +// which is what makes Equal blind to order and duplicates. +func canonicalKeys(ss Specifiers) map[string]struct{} { + keys := make(map[string]struct{}, ss.Len()) + for _, s := range ss.List() { + op, operand := s.canonicalSpec() + keys[op+operand] = struct{}{} + } + return keys +} + +// And returns the intersection of two specifier sets: every specifier from +// both, which is upstream's `SpecifierSet.__and__`. +// +// The pre-release policies are combined rather than dropped. PreReleasesAuto +// on one side yields to the other; two identical explicit policies survive; +// Include on one side and Exclude on the other is a contradiction and returns +// ErrPreReleaseConflict, as upstream raises ValueError. +func (ss Specifiers) And(other Specifiers) (Specifiers, error) { + pre, err := combinePreReleases(ss.conf.preReleases, other.conf.preReleases) + if err != nil { + return Specifiers{}, err + } + + combined := append(ss.List(), other.List()...) + // Re-stamp each member with the combined policy so a specifier read back + // off the result answers PreReleases consistently with the set. + for i := range combined { + combined[i].pre = pre + } + + return Specifiers{ + specifiers: [][]Specifier{combined}, + conf: conf{preReleases: pre}, + }, nil +} + +func combinePreReleases(left, right PreReleases) (PreReleases, error) { + switch { + case left == PreReleasesAuto: + return right, nil + case right == PreReleasesAuto, left == right: + return left, nil + default: + return PreReleasesAuto, ErrPreReleaseConflict + } +} + +// NewSpecifiersFrom builds a set from already-parsed specifiers, which is +// upstream's `SpecifierSet(iterable_of_Specifier)`. The members are used as +// given; no re-parsing happens. +func NewSpecifiersFrom(specs []Specifier, opts ...SpecifierOption) Specifiers { + c := new(conf) + for _, o := range opts { + o.apply(c) + } + group := make([]Specifier, len(specs)) + copy(group, specs) + if c.preReleases != PreReleasesAuto { + for i := range group { + group[i].pre = c.preReleases + } + } + return Specifiers{specifiers: [][]Specifier{group}, conf: *c} +} + +//------------------------------------------------------------------- +// The filter engine +//------------------------------------------------------------------- + +// Filterer is the filtering behavior shared by Specifier and Specifiers. +// +// It is a sealed interface — its only method is unexported — because the +// pre-release bookkeeping in the implementations below is subtle enough that a +// third-party implementation would almost certainly get the "offer a +// pre-release only when nothing else matched" rule wrong. +type Filterer interface { + // filterKeep returns, for each input string, whether it is offered. + filterKeep(items []string, fc filterConf) []bool +} + +// FilterBy filters an arbitrary slice, deriving each element's version string +// with key. It is upstream's `key=` parameter on filter, expressed as a free +// generic function because Go methods cannot take type parameters. +// +// FilterBy(specs, releases, func(r Release) string { return r.Version }) +func FilterBy[T any](f Filterer, items []T, key func(T) string, opts ...FilterOption) []T { + return filterGeneric(f, items, key, opts) +} + +func filterGeneric[T any](f Filterer, items []T, key func(T) string, opts []FilterOption) []T { + strs := make([]string, len(items)) + for i, it := range items { + strs[i] = key(it) + } + keep := f.filterKeep(strs, newFilterConf(opts)) + + out := make([]T, 0, len(items)) + for i, k := range keep { + if k { + out = append(out, items[i]) + } + } + return out +} + +// filterKeep implements upstream's Specifier.filter for a single specifier. +// +// The three-way bookkeeping is upstream's and is easy to get subtly wrong, so +// it is spelled out: a matching pre-release is yielded immediately when the +// policy includes pre-releases, buffered when the policy is unresolved and the +// specifier does not forbid them, and dropped otherwise. The buffer is only +// released if nothing was yielded directly — that is the "offer a pre-release +// when there is nothing else" rule, and it is why Filter's answer for one +// item can differ from its answer for that item alongside a final release. +func (s Specifier) filterKeep(items []string, fc filterConf) []bool { + keep := make([]bool, len(items)) + + // A per-call policy wins over the one the specifier carries; otherwise the + // specifier's resolved policy decides. + effective := fc.preReleases + if effective == PreReleasesAuto { + effective = s.PreReleases() + } + includePre := effective == PreReleasesInclude + + // callerUnset and specForbids gate the buffer, mirroring upstream's + // `prereleases is None and self._prereleases is not False`. Note that + // specForbids reads the RAW policy the specifier was built with, not the + // resolved one: an autodetected Exclude still buffers, an explicit one + // does not. + callerUnset := fc.preReleases == PreReleasesAuto + specForbids := s.pre == PreReleasesExclude + + var buffered []int + foundOffered := false + + for i, item := range items { + v, err := Parse(item) + if err != nil { + // Not a PEP 440 version. Only arbitrary equality can match it, and + // when it does it is offered unconditionally: there is no way to + // tell whether an opaque token is a pre-release, so the + // pre-release rules do not apply to it at all. + if s.op == "===" && strings.EqualFold(item, s.operand) { + keep[i] = true + } + continue + } + + var match bool + if s.op == "===" { + match = strings.EqualFold(item, s.operand) + } else { + match = s.Check(v) + } + if !match { + continue + } + + switch { + case !v.IsPreRelease() || includePre: + foundOffered = true + keep[i] = true + case callerUnset && !specForbids: + buffered = append(buffered, i) + } + } + + if !foundOffered && callerUnset && !specForbids { + for _, i := range buffered { + keep[i] = true + } + } + + return keep +} + +// filterKeep implements upstream's SpecifierSet.filter. +func (ss Specifiers) filterKeep(items []string, fc filterConf) []bool { + // An unset per-call policy falls back to the set's resolved policy, which + // may itself be unresolved. + policy := fc.preReleases + if policy == PreReleasesAuto { + policy = ss.PreReleases() + } + + if ss.Len() == 0 { + return ss.filterEmpty(items, policy) + } + + // With the policy still unresolved, let every match through the + // per-specifier pass and decide about pre-releases once, at the end, over + // the versions that satisfied the WHOLE set. Deciding per specifier would + // release a buffered pre-release that a later specifier rejects. + inner := policy + if inner == PreReleasesAuto { + inner = PreReleasesInclude + } + + matched := ss.matchAll(items, inner == PreReleasesExclude) + + if policy != PreReleasesAuto { + return matched + } + return applyPEP440Preference(items, matched) +} + +// matchAll keeps the items that satisfy the set's operators. Membership is +// OR-of-AND: an item passes if it satisfies every specifier of any one group. +// Upstream has a single group, so for a set built from a Python-style +// comma-separated string this is plain conjunction. +func (ss Specifiers) matchAll(items []string, excludePre bool) []bool { + keep := make([]bool, len(items)) + for i, item := range items { + v, err := Parse(item) + if err != nil { + // Only a set made entirely of matching `===` specifiers can hold + // a non-version. + keep[i] = ss.allArbitraryMatch(item) + continue + } + if excludePre && v.IsPreRelease() { + continue + } + for _, group := range ss.specifiers { + if groupMatches(group, item, v) { + keep[i] = true + break + } + } + } + return keep +} + +func groupMatches(group []Specifier, item string, v Version) bool { + for _, s := range group { + var ok bool + if s.op == "===" { + ok = strings.EqualFold(item, s.operand) + } else { + ok = s.Check(v) + } + if !ok { + return false + } + } + return true +} + +func (ss Specifiers) allArbitraryMatch(item string) bool { + for _, group := range ss.specifiers { + all := len(group) > 0 + for _, s := range group { + if s.op != "===" || !strings.EqualFold(item, s.operand) { + all = false + break + } + } + if all { + return true + } + } + return false +} + +// filterEmpty is the empty-set arm of SpecifierSet.filter. An empty set +// constrains nothing, so the pre-release policy is the only thing left to +// apply. +func (ss Specifiers) filterEmpty(items []string, policy PreReleases) []bool { + keep := make([]bool, len(items)) + switch policy { + case PreReleasesInclude: + for i := range keep { + keep[i] = true + } + return keep + case PreReleasesExclude: + for i, item := range items { + v, err := Parse(item) + keep[i] = err != nil || !v.IsPreRelease() + } + return keep + default: + for i := range keep { + keep[i] = true + } + return applyPEP440Preference(items, keep) + } +} + +// applyPEP440Preference is upstream's _pep440_filter_prereleases: of the +// candidates that already matched, offer the final releases; offer the +// pre-releases only if there are no final releases at all. +// +// Items that are not parseable versions have already passed every specifier +// (only `===` can admit them) and cannot be classified as pre-release or not, +// so they are always offered. +func applyPEP440Preference(items []string, matched []bool) []bool { + keep := make([]bool, len(items)) + var nonFinal []int + foundFinal := false + + for i, item := range items { + if !matched[i] { + continue + } + v, err := Parse(item) + if err != nil { + keep[i] = true + continue + } + if !v.IsPreRelease() { + foundFinal = true + keep[i] = true + continue + } + nonFinal = append(nonFinal, i) + } + + if !foundFinal { + for _, i := range nonFinal { + keep[i] = true + } + } + return keep +} + +// Compile-time proof that both types implement the filter shape FilterBy +// accepts, so a signature change cannot silently exclude one of them. +var ( + _ Filterer = Specifier{} + _ Filterer = Specifiers{} +) diff --git a/version/specifier_test.go b/version/specifier_test.go index 5f0f377..f8ee1f4 100644 --- a/version/specifier_test.go +++ b/version/specifier_test.go @@ -464,6 +464,21 @@ func TestNewRSpecifiers_UsesProvidedSanitizer(t *testing.T) { assert.True(t, specs.Check(v)) } +// TestVersion_CheckWithPreRelease pins the corrected meaning of +// WithPreRelease(true): it is a candidate-SELECTION policy and does not +// suppress the operator-level pre-release guards. +// +// The {"2.0a1", "<2", true} case this table used to assert was a divergence. +// Measured against pypa/packaging 26.2, `<2` does not contain `2.0a1` under +// ANY pre-release policy: +// +// Specifier("<2", prereleases=True).contains("2.0a1") -> False +// Specifier("<2").contains("2.0a1") -> False +// Specifier("<2", prereleases=False).contains("2.0a1") -> False +// +// The old `true` came from WithPreRelease(true) setting a flag that made +// Version.IsPreRelease report false, which disabled the guard in +// specifierLessThan. See rstudio/package-manager#19383. func TestVersion_CheckWithPreRelease(t *testing.T) { tests := []struct { version string @@ -471,7 +486,7 @@ func TestVersion_CheckWithPreRelease(t *testing.T) { want bool }{ {"1.3.4", "< 2.0", true}, - {"2.0a1", "<2", true}, + {"2.0a1", "<2", false}, {"2.1a1", "<2", false}, } for _, tt := range tests { diff --git a/version/version.go b/version/version.go index 980b5f7..4fd5b82 100644 --- a/version/version.go +++ b/version/version.go @@ -54,15 +54,14 @@ const ( // Version represents a single version. type Version struct { - epoch part.BigInt - release []part.BigInt - pre letterNumber - post letterNumber - dev letterNumber - local string - key key - preReleaseIncluded bool - original string + epoch part.BigInt + release []part.BigInt + pre letterNumber + post letterNumber + dev letterNumber + local string + key key + original string } type key struct { @@ -473,14 +472,35 @@ func (v Version) Public() string { return strings.SplitN(v.String(), "+", 2)[0] } -// IsPreRelease returns if it is a pre-release +// IsPreRelease reports whether this is a pre-release: it has a pre-release +// segment (a1, b2, rc3) or a dev segment. +// +// ⚠️ This is a property of the version, and nothing else may override it. A +// pre-release policy (see PreReleases) decides whether a pre-release is +// *offered* as a candidate; it does not make a pre-release stop being one. An +// earlier version of this package let WithPreRelease(true) flip this method to +// false, which silently disabled the operator-level guards in the comparison +// functions below and made `<2` match `2.0.dev1` — a result pypa/packaging +// 26.2 rejects under every pre-release policy. func (v Version) IsPreRelease() bool { - if v.preReleaseIncluded { - return false - } return !v.pre.isNull() || !v.dev.isNull() } +// trimmedRelease renders the version like String, but with trailing zero +// components dropped from the release segment (always keeping at least one), +// which is the canonical form upstream's canonicalize_version produces via +// _TrimmedRelease. Used by Specifier equality. +func (v Version) trimmedRelease() string { + trimmed := v + rel := v.release + i := len(rel) + for i > 1 && rel[i-1].Compare(part.Zero) == 0 { + i-- + } + trimmed.release = rel[:i] + return trimmed.String() +} + // IsPostRelease returns if it is a post-release func (v Version) IsPostRelease() bool { return !v.post.isNull() From e93e42574fa7d250312b9a50544deb864b76cb59 Mon Sep 17 00:00:00 2001 From: Jonathan Yoder Date: Mon, 10 Aug 2026 11:58:18 -0400 Subject: [PATCH 2/7] Respect the OR-of-ANDs structure in the new query API Three review findings with one root cause: Specifiers is an OR of AND groups, and the new query API treated it as a flat bag of specifiers. HIGH -- an empty "||" segment silently disabled the whole constraint. Splitting on "||" produced a blank segment for a leading, trailing or doubled operator; parseGroup turned a blank segment into an empty AND-group; and an empty AND-group matches every version, so Check's OR swallowed every other group. ">=1||" parsed and then admitted 0.1, a version below its own floor, with nothing erroring and nothing logged. This was a regression introduced by this branch: at v0.4.0 the same input was an error. The R entry point shares the path and is what PPM uses for R version constraints. The universal set now has exactly one producer, universalSpecifiers, reached only when the ENTIRE input is blank. parseGroup can no longer return an empty group and says so; its doc comment previously read as justifying the behavior, which would have invited someone to restore it on purpose. MEDIUM -- And concatenated members instead of distributing, so (A||B) AND C became A AND B AND C. That is strictly narrower and usually unsatisfiable: (==1.0||==2.0) AND <3.0 matched NOTHING, rejecting both versions it should have admitted. Now distributes to (==1.0,<3.0) || (==2.0,<3.0). Chose distribution over erroring on multi-group operands because it is the correct semantics and And is new API, so there is no compatibility cost. The universal set is now the identity of And in both positions, which a cartesian product over zero groups would not have been. MEDIUM -- Equal compared a flattened member set, so ">=1||<2" (admits everything) compared equal to ">=1,<2" (admits the intersection). Now compares the set of canonicalized AND-groups: still blind to group order, within-group order, duplicates and pre-release policy, but no longer blind to which members share a group. For a single-group set -- everything a Python-style comma-separated string produces, and so everything the upstream conformance tables exercise -- this reduces exactly to the previous behavior. Audited every operation that consumes a flattened view. Check, String, Contains, Filter, matchAll and allArbitraryMatch already walk the groups. Len (a count), List (iteration) and Specifiers.PreReleases (a global policy hint, upstream's `any(s.prereleases for s in self._specs)`) are genuinely structure-independent, and there is now a test pinning that rather than leaving it as prose. List's doc comment warns against using it as a basis for semantics, naming both bugs it caused. Every test verified RED before the fix: 6 of 8 new test functions and 11 subtests failed on the parent commit, with ">=1||" reported as admitting 0.1 and the And result rejecting all three probe versions. The two that were already green are the preserved-behavior control (empty input stays universal, comma handling unchanged) and the Contains/Filter pin. Measured: "||" does not occur at all in real CRAN data (0 of 59,139 constraint occurrences), so the narrowing affects nothing real. The extraction pattern was proved to flag the three malformed shapes and not the well-formed ">=1||<2". Refs rstudio/package-manager#19383 Co-Authored-By: Claude Opus 5 (1M context) --- CHANGELOG.md | 21 ++ version/or_group_structure_test.go | 397 +++++++++++++++++++++++++++++ version/specifier.go | 113 +++++++- version/specifier_query.go | 108 ++++++-- 4 files changed, 608 insertions(+), 31 deletions(-) create mode 100644 version/or_group_structure_test.go diff --git a/CHANGELOG.md b/CHANGELOG.md index b38be99..9ae41da 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -100,6 +100,19 @@ mistaken for a safe patch upgrade. `len(SpecifierSet(">=1.0") & SpecifierSet(">=1.0"))` is 2 in packaging 26.2 — while `Equal` is blind to order and duplicates. + ⚠️ **`And` and `Equal` respect this type's OR-of-ANDs shape**, which upstream has no + equivalent of (the `||` operator is this package's extension for the R constraint + path). `And` **distributes**: `(A||B) AND C` is `(A,C) || (B,C)`, not `A AND B AND C`. + `Equal` compares the set of canonicalized AND-groups, so `">=1||<2"` does **not** equal + `">=1,<2"` — they hold the same members but mean opposite things, the first admitting + every version and the second only their intersection. For a single-group set, which is + everything a Python-style comma-separated string produces, both reduce exactly to + upstream's behavior. + + ⚠️ **`List()` is for iteration, not semantics.** It flattens across OR-groups, so it + cannot be used to decide what a set matches or whether two sets are the same. Its doc + comment says so. `Len()` likewise counts members across all groups. + - `marker.Environment.With(map[string]string)`, `Environment.Lookup(name)` and `marker.VariableNames()`: the override seam a **partial** marker environment needs. @@ -118,6 +131,14 @@ mistaken for a safe patch upgrade. fix covered only the zero-value/no-groups arm; this is the empty-input arm that survived it. + ⚠️ **Only a wholly blank input is universal.** A blank `||` segment is an error: + `">=1||"`, `"||>=1"` and `">=1||||<2"` are rejected. Since `||` is an OR and an empty + AND-group matches everything, allowing one would mean a trailing-`||` typo *disabled* + the constraint rather than narrowing it — `">=1||"` would admit `0.1` — with nothing + erroring and nothing logged. Behavior is unchanged from 0.4.0, where such input was + also an error. Measured against real CRAN data for the R path: `||` does not occur at + all in 59,139 constraint occurrences, so nothing real is affected. + - The six `MustParse` calls on the matching hot path (`version/specifier.go`) no longer panic on an operand that is not a valid version; a comparison that cannot be made yields no match. diff --git a/version/or_group_structure_test.go b/version/or_group_structure_test.go new file mode 100644 index 0000000..bba8617 --- /dev/null +++ b/version/or_group_structure_test.go @@ -0,0 +1,397 @@ +// SPDX-License-Identifier: Apache-2.0 OR MIT + +// Regression tests for one theme with three symptoms: Specifiers is an +// OR-of-ANDs, and treating it as a flat bag of specifiers is wrong. +// +// HIGH an empty "||" segment became an empty AND-group, which matches +// everything, so ">=1||" silently admitted every version. +// MEDIUM And concatenated the two operands' members instead of distributing, +// so (A||B) AND C became A AND B AND C and matched nothing. +// MEDIUM Equal compared a flattened member set, so ">=1||<2" (admits +// everything) compared equal to ">=1,<2" (admits the intersection). +// +// pypa/packaging cannot arbitrate any of these: it has no "||" operator at all, +// since the OR syntax is this package's extension for the R constraint path. The +// reference here is the operator's own meaning. + +package version + +import ( + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// identitySanitizer, the no-op sanitizer the R entry point requires, is +// declared in adjacent_constraint_test.go and reused here. + +// A malformed "||" expression must be an ERROR. The failure mode being guarded +// against is not "accepts something odd" -- it is that ">=1||" parsed happily +// and then admitted 0.1, a version below its own floor, with nothing logged and +// nothing failing. +func TestEmptyOrSegmentIsRejected(t *testing.T) { + malformed := []string{ + ">=1||", // trailing + "||>=1", // leading + ">=1||||<2", // doubled + "||", // nothing but the operator + ">=1|| ||<2", // doubled with whitespace + " || >=1", // leading with whitespace + ">=1,<2||", // trailing after a multi-member group + "||||", // several + } + + for _, in := range malformed { + t.Run(in, func(t *testing.T) { + _, err := NewSpecifiers(in) + assert.Error(t, err, "NewSpecifiers(%q) must be an error", in) + + // The R entry point shares this code path, and is the one PPM uses + // for R version constraints. + _, err = NewRSpecifiers(in, identitySanitizer) + assert.Error(t, err, "NewRSpecifiers(%q) must be an error", in) + }) + } +} + +// The specific consequence, asserted directly rather than only via the parse +// error: a trailing "||" must never be able to turn a real constraint into one +// that admits everything. +func TestEmptyOrSegmentCannotDisableAConstraint(t *testing.T) { + below := MustParse("0.1") + + for _, in := range []string{">=1||", "||>=1", ">=1||||<2"} { + t.Run(in, func(t *testing.T) { + ss, err := NewSpecifiers(in) + if err == nil { + assert.False(t, ss.Check(below), + "%q parsed, and then admitted 0.1 -- the constraint was disabled, not narrowed", in) + t.Fatalf("%q must not parse at all", in) + } + + // A well-formed OR of the same members still behaves like an OR. + ok, err := NewSpecifiers(">=1||<2") + require.NoError(t, err) + assert.True(t, ok.Check(below), "0.1 satisfies the <2 branch") + assert.True(t, ok.Check(MustParse("99")), "99 satisfies the >=1 branch") + }) + } +} + +// PRESERVED-BEHAVIOR CONTROL. The "||" fix must not disturb the empty-input +// universal set, nor comma handling inside a group. +// +// ⚠️ Note what the comma rows actually assert. `packaging` 26.2 ACCEPTS ",>=1" +// and ">=1,,<2" (it drops empty comma-split items) and this package rejects +// both -- a real, still-open divergence tracked in +// rstudio/package-manager#19391 and NOT fixed here. The rows pin the current +// behavior so that the "||" change is demonstrably orthogonal to it; they are +// not a claim that rejecting them is correct. +func TestOrFixPreservesEmptyInputAndCommaHandling(t *testing.T) { + t.Run("empty input is still the universal set", func(t *testing.T) { + for _, in := range []string{"", " ", "\t"} { + ss, err := NewSpecifiers(in) + require.NoError(t, err, "input %q", in) + assert.Equal(t, 0, ss.Len()) + assert.Equal(t, "", ss.String()) + for _, v := range []string{"0", "0.1", "1.0", "2.0a1", "1!3.0", "1.0+local"} { + assert.True(t, ss.Check(MustParse(v)), "%q must admit %s", in, v) + } + + rs, err := NewRSpecifiers(in, identitySanitizer) + require.NoError(t, err, "R input %q", in) + assert.True(t, rs.Check(MustParse("0.1"))) + } + }) + + t.Run("comma handling is unchanged", func(t *testing.T) { + // Rejected before this change and rejected after it. See the divergence + // note above. + for _, in := range []string{",>=1", ">=1,,<2"} { + _, err := NewSpecifiers(in) + assert.Error(t, err, "%q: still rejected (upstream accepts; #19391)", in) + } + // A trailing comma is tolerated, and stays tolerated. + ss, err := NewSpecifiers(">=1,") + require.NoError(t, err) + assert.Equal(t, 1, ss.Len()) + }) + + t.Run("well-formed OR groups still parse", func(t *testing.T) { + ss, err := NewSpecifiers(">=1.0,<2.0||>=3.0") + require.NoError(t, err) + assert.True(t, ss.Check(MustParse("1.5"))) + assert.True(t, ss.Check(MustParse("4.0"))) + assert.False(t, ss.Check(MustParse("2.5"))) + }) + + t.Run("the R wildcard segment still works", func(t *testing.T) { + rs, err := NewRSpecifiers("*", identitySanitizer) + require.NoError(t, err) + assert.True(t, rs.Check(MustParse("1.0"))) + + rs, err = NewRSpecifiers("*||>=3.0", identitySanitizer) + require.NoError(t, err) + assert.True(t, rs.Check(MustParse("1.0"))) + }) +} + +// And must DISTRIBUTE over the OR-groups. Concatenating the members produced a +// strictly narrower constraint that usually matched nothing. +func TestAndDistributesOverOrGroups(t *testing.T) { + left, err := NewSpecifiers("==1.0||==2.0") + require.NoError(t, err) + right, err := NewSpecifiers("<3.0") + require.NoError(t, err) + + got, err := left.And(right) + require.NoError(t, err) + + // (==1.0 || ==2.0) AND <3.0 == (==1.0,<3.0) || (==2.0,<3.0) + assert.True(t, got.Check(MustParse("1.0")), "1.0 satisfies the first branch") + assert.True(t, got.Check(MustParse("2.0")), "2.0 satisfies the second branch") + assert.False(t, got.Check(MustParse("5.0")), "5.0 fails the <3.0 conjunct") + + // The concatenating version returned a single unsatisfiable group, so it + // answered false for every one of the three. + assert.NotEqual(t, 1, len(got.specifiers), + "the result must keep both branches, not collapse to one AND-group") +} + +func TestAndDistributesBothSides(t *testing.T) { + left, err := NewSpecifiers(">=1.0,<2.0||>=10.0,<11.0") + require.NoError(t, err) + right, err := NewSpecifiers("!=1.5||!=10.5") + require.NoError(t, err) + + got, err := left.And(right) + require.NoError(t, err) + assert.Equal(t, 4, len(got.specifiers), "2 groups AND 2 groups distributes to 4") + + // 1.5 is excluded by !=1.5 but the !=10.5 branch still admits it. + assert.True(t, got.Check(MustParse("1.5"))) + assert.True(t, got.Check(MustParse("1.2"))) + assert.True(t, got.Check(MustParse("10.2"))) + assert.False(t, got.Check(MustParse("5.0")), "outside both ranges") +} + +// The universal set is the identity of And, in both positions. A cartesian +// product against a set with zero groups would otherwise have produced zero +// groups and quietly discarded the other operand's constraints. +func TestAndUniversalIsIdentity(t *testing.T) { + constrained, err := NewSpecifiers(">=1.0,<2.0") + require.NoError(t, err) + empty, err := NewSpecifiers("") + require.NoError(t, err) + + for name, combine := range map[string]func() (Specifiers, error){ + "universal on the right": func() (Specifiers, error) { return constrained.And(empty) }, + "universal on the left": func() (Specifiers, error) { return empty.And(constrained) }, + "zero value on the right": func() (Specifiers, error) { + return constrained.And(Specifiers{}) + }, + "zero value on the left": func() (Specifiers, error) { + return Specifiers{}.And(constrained) + }, + } { + t.Run(name, func(t *testing.T) { + got, err := combine() + require.NoError(t, err) + assert.True(t, got.Check(MustParse("1.5")), "must still admit what the constraint admits") + assert.False(t, got.Check(MustParse("2.5")), "must still reject what the constraint rejects") + assert.True(t, got.Equal(constrained), "universal AND X must equal X") + }) + } +} + +// Equal must respect conjunction boundaries: an OR and an AND of the same two +// members are different predicates. +func TestEqualRespectsOrGroupBoundaries(t *testing.T) { + or, err := NewSpecifiers(">=1||<2") + require.NoError(t, err) + and, err := NewSpecifiers(">=1,<2") + require.NoError(t, err) + + // They genuinely differ: the OR admits everything, the AND does not. + assert.True(t, or.Check(MustParse("0.5")), "the OR admits 0.5 via the <2 branch") + assert.False(t, and.Check(MustParse("0.5")), "the AND rejects 0.5 via >=1") + + assert.False(t, or.Equal(and), `">=1||<2" must not equal ">=1,<2"`) + assert.False(t, and.Equal(or), "Equal must be symmetric") +} + +// What Equal must still ignore, so the group-awareness does not overshoot. +func TestEqualStillIgnoresOrderDuplicatesAndPolicy(t *testing.T) { + tests := []struct { + left, right string + want bool + }{ + // Within-group order and duplicates. + {">=1,<2", "<2,>=1", true}, + {">=1,>=1", ">=1", true}, + {">=1.0.0", ">=1", true}, + // Group order. + {">=1||<2", "<2||>=1", true}, + {"==1.0||==2.0||==3.0", "==3.0||==1.0||==2.0", true}, + // Duplicated whole groups collapse, because the keys are a SET. + {">=1||>=1", ">=1", true}, + // Genuinely different. + {">=1,<2", ">=1", false}, + {">=1||<2", ">=1", false}, + {"==1.0||==2.0", "==1.0||==3.0", false}, + } + + for _, tt := range tests { + t.Run(tt.left+"__"+tt.right, func(t *testing.T) { + l, err := NewSpecifiers(tt.left) + require.NoError(t, err) + r, err := NewSpecifiers(tt.right) + require.NoError(t, err) + assert.Equal(t, tt.want, l.Equal(r)) + assert.Equal(t, tt.want, r.Equal(l), "Equal must be symmetric") + }) + } + + // The pre-release policy is still not part of equality. + a, err := NewSpecifiers(">=1||<2", WithPreReleases(PreReleasesInclude)) + require.NoError(t, err) + b, err := NewSpecifiers(">=1||<2", WithPreReleases(PreReleasesExclude)) + require.NoError(t, err) + assert.True(t, a.Equal(b)) +} + +// And and Equal must agree: the distributed result must equal the set written +// out by hand. If they disagreed, one of the two is wrong and neither's own +// tests would say which. +func TestAndAgreesWithEqual(t *testing.T) { + left, err := NewSpecifiers("==1.0||==2.0") + require.NoError(t, err) + right, err := NewSpecifiers("<3.0") + require.NoError(t, err) + + got, err := left.And(right) + require.NoError(t, err) + + want, err := NewSpecifiers("==1.0,<3.0||==2.0,<3.0") + require.NoError(t, err) + assert.True(t, got.Equal(want), "distributed And must equal the hand-written distribution") + + // And it must NOT equal the concatenation, which is what it used to produce. + concatenated, err := NewSpecifiers("==1.0,==2.0,<3.0") + require.NoError(t, err) + assert.False(t, got.Equal(concatenated), + "the distributed result must not equal the flattened conjunction") +} + +// Contains and Filter already walk the groups; pin that, so a later refactor +// toward List() cannot regress them the way Equal and And were regressed. +func TestContainsAndFilterRespectOrGroups(t *testing.T) { + ss, err := NewSpecifiers("==1.0||==2.0") + require.NoError(t, err) + + assert.True(t, ss.Contains("1.0")) + assert.True(t, ss.Contains("2.0")) + assert.False(t, ss.Contains("3.0")) + + assert.Equal(t, []string{"1.0", "2.0"}, ss.Filter([]string{"1.0", "2.0", "3.0"})) + + // A flattened reading would be the unsatisfiable ==1.0 AND ==2.0. + assert.NotEmpty(t, ss.Filter([]string{"1.0"}), + "a flattened reading would match nothing at all") + + // ContainsInstalled delegates to Contains, so it inherits the group walk. + assert.True(t, ss.ContainsInstalled("1.0")) + assert.False(t, ss.ContainsInstalled("3.0")) + + // The OR must survive an explicit pre-release policy too, since that takes + // a different branch through filterKeep. + for _, policy := range []PreReleases{PreReleasesAuto, PreReleasesInclude, PreReleasesExclude} { + assert.True(t, ss.Contains("1.0", WithPreReleases(policy)), "policy %s", policy) + assert.True(t, ss.Contains("2.0", WithPreReleases(policy)), "policy %s", policy) + assert.False(t, ss.Contains("3.0", WithPreReleases(policy)), "policy %s", policy) + } +} + +// The audit's other half: the operations that consume a FLATTENED view are +// documented as doing so because they are genuinely structure-independent, and +// this pins that claim rather than leaving it as prose. +// +// Len - a COUNT, not a predicate. Documented as the total across groups. +// Its one semantic use is `Len() == 0` meaning "constrains nothing", +// which stays correct because the universal set is the only thing that +// can produce an empty group. +// List - ITERATION only; warned against in its doc comment. +// PreReleases - a global policy hint ("does any member imply pre-releases"), +// which is upstream's `any(s.prereleases for s in self._specs)`. It +// does not decide what matches, so grouping cannot change it. +func TestFlattenedOperationsAreStructureIndependent(t *testing.T) { + or, err := NewSpecifiers(">=1.0||<2.0") + require.NoError(t, err) + and, err := NewSpecifiers(">=1.0,<2.0") + require.NoError(t, err) + + t.Run("Len counts members either way", func(t *testing.T) { + assert.Equal(t, 2, or.Len()) + assert.Equal(t, 2, and.Len()) + assert.Len(t, or.List(), or.Len()) + assert.Len(t, and.List(), and.Len()) + }) + + t.Run("Len()==0 means constrains nothing, and only the universal set does", func(t *testing.T) { + universal, err := NewSpecifiers("") + require.NoError(t, err) + assert.Equal(t, 0, universal.Len()) + assert.Equal(t, 0, Specifiers{}.Len()) + + // Anything that parsed from a non-blank input has at least one member, + // so it can never be mistaken for the universal set. + for _, in := range []string{">=1", ">=1||<2", ">=1,<2", "*", ">=1,"} { + ss, err := NewSpecifiers(in) + require.NoError(t, err, in) + assert.NotZero(t, ss.Len(), "%q must not look like the universal set", in) + } + }) + + t.Run("PreReleases is a global hint, unaffected by grouping", func(t *testing.T) { + // A pre-release operand in either position resolves the set to Include, + // whether the members are ANDed or ORed. + orPre, err := NewSpecifiers(">=1.0||<2.0.dev1") + require.NoError(t, err) + andPre, err := NewSpecifiers(">=1.0,<2.0.dev1") + require.NoError(t, err) + assert.Equal(t, PreReleasesInclude, orPre.PreReleases()) + assert.Equal(t, PreReleasesInclude, andPre.PreReleases()) + + // And with no pre-release operand, both stay unresolved. + assert.Equal(t, PreReleasesAuto, or.PreReleases()) + assert.Equal(t, PreReleasesAuto, and.PreReleases()) + }) +} + +// NewSpecifiersFrom builds a single AND-group, which is correct: it is +// upstream's `SpecifierSet(iterable_of_Specifier)`, and upstream has no OR. +// Pinned so nobody "fixes" it into something that spreads members across groups. +func TestNewSpecifiersFromBuildsOneAndGroup(t *testing.T) { + lower, err := NewSpecifier(">=1.0") + require.NoError(t, err) + upper, err := NewSpecifier("<2.0") + require.NoError(t, err) + + ss := NewSpecifiersFrom([]Specifier{lower, upper}) + assert.Len(t, ss.specifiers, 1, "one AND-group, not one group per member") + + // Conjunction, so the midpoint matches and the outside does not. + assert.True(t, ss.Check(MustParse("1.5"))) + assert.False(t, ss.Check(MustParse("2.5"))) + assert.False(t, ss.Check(MustParse("0.5"))) + + // If it had built two OR-groups instead, 0.5 would match the <2.0 branch. + parsed, err := NewSpecifiers(">=1.0,<2.0") + require.NoError(t, err) + assert.True(t, ss.Equal(parsed)) + + or, err := NewSpecifiers(">=1.0||<2.0") + require.NoError(t, err) + assert.False(t, ss.Equal(or)) +} diff --git a/version/specifier.go b/version/specifier.go index a1ba81f..05b5cc8 100644 --- a/version/specifier.go +++ b/version/specifier.go @@ -174,8 +174,16 @@ func newRSpecifiers(v string, sanitizer func(string) string, opts ...SpecifierOp o.apply(c) } + segments, universal, err := splitOrSegments(v) + if err != nil { + return Specifiers{}, err + } + if universal { + return universalSpecifiers(*c), nil + } + var sss [][]Specifier - for _, vv := range strings.Split(v, "||") { + for _, vv := range segments { if strings.TrimSpace(vv) == "*" { vv = ">=0.0.0" } @@ -204,8 +212,16 @@ func newSpecifiers(v string, sanitizer func(string) string, opts ...SpecifierOpt o.apply(c) } + segments, universal, err := splitOrSegments(v) + if err != nil { + return Specifiers{}, err + } + if universal { + return universalSpecifiers(*c), nil + } + var sss [][]Specifier - for _, vv := range strings.Split(v, "||") { + for _, vv := range segments { if strings.TrimSpace(vv) == "*" { vv = ">=0.0.0" } @@ -224,6 +240,56 @@ func newSpecifiers(v string, sanitizer func(string) string, opts ...SpecifierOpt } +// splitOrSegments splits the input on the "||" OR operator. +// +// universal is true when the ENTIRE input is empty or whitespace, which is the +// one and only way to get a set that constrains nothing. In that case segments +// is nil and the caller must not parse anything. +// +// ⚠️ An empty "||" segment is an ERROR, not the universal set. +// +// This is the whole point of the function, and it is worth being explicit about +// why, because the obvious-looking alternative is a silent, invisible failure. +// "||" is an OR, and Check admits a version if ANY group matches; a group with +// no specifiers in it matches everything. So if ">=1||" were allowed to parse +// as `>=1 OR (nothing)`, the trailing typo would not narrow the constraint or +// raise an error -- it would DISABLE it, and ">=1||" would admit 0.1. The R +// entry point shares this path and is what PPM uses for R version constraints, +// so the visible symptom would be "the wrong versions were allowed", with +// nothing logged and nothing failing. +// +// A leading, trailing or doubled "||" is therefore rejected. Note that this is +// specifically about the "||" boundary: comma handling inside a group is a +// separate question, decided in parseGroup. +func splitOrSegments(v string) (segments []string, universal bool, err error) { + if strings.TrimSpace(v) == "" { + return nil, true, nil + } + + segments = strings.Split(v, "||") + for _, segment := range segments { + if strings.TrimSpace(segment) == "" { + return nil, false, fmt.Errorf( + "improper constraint: empty || segment in %q (a leading, trailing or doubled || is not allowed)", v) + } + } + return segments, false, nil +} + +// universalSpecifiers returns the set that constrains nothing: exactly one +// AND-group, containing no specifiers. +// +// It is spelled as one EMPTY group rather than as zero groups so that the two +// readings of "no constraints" cannot drift apart -- Check treats zero groups +// and an empty group the same way, and both mean "admits every version" (see +// Check, and rstudio/package-manager#19366). +func universalSpecifiers(c conf) Specifiers { + return Specifiers{ + specifiers: [][]Specifier{nil}, + conf: c, + } +} + // NewSpecifier parses a single PEP 440 version specifier, such as `>=1.2.3`. // // It is the singular counterpart to NewSpecifiers and mirrors upstream's @@ -253,22 +319,38 @@ func NewSpecifier(s string, opts ...SpecifierOption) (Specifier, error) { // parseGroup parses one AND-group: a comma-separated run of specifiers. // -// An empty group is legal and yields zero specifiers, which is how -// `NewSpecifiers("")` becomes the universal set rather than an error. Upstream -// reaches the same place from the other end, by dropping empty items after -// splitting on the comma (`[s.strip() for s in specifiers.split(",") if -// s.strip()]`), which is also why it accepts a leading or doubled comma. +// ⚠️ parseGroup NEVER returns an empty group, and must not be changed to. +// +// An empty AND-group matches every version (a conjunction over no constraints +// is vacuously true), so inside an OR it does not widen the set a little -- it +// makes the whole set universal. Returning one from here for a blank input is +// what made ">=1||" admit 0.1: the trailing "||" produced a blank segment, the +// blank segment produced an empty group, and the empty group swallowed the +// ">=1". A malformed constraint went from "error" to "silently allows +// everything". +// +// The universal set has exactly one producer, and it is not this function: see +// universalSpecifiers, reached only when the ENTIRE input is blank. Callers +// guarantee that by rejecting blank "||" segments in splitOrSegments, so a +// blank input reaching here is a caller bug and is reported as an error. +// +// A blank group is not the same question as a blank comma-separated ITEM. +// Upstream drops empty comma-split items (`[s.strip() for s in +// specifiers.split(",") if s.strip()]`), which is why `packaging` accepts +// ",>=1" and ">=1,,<2"; this package still rejects both, via +// validConstraintRegexp, and that remaining divergence is tracked in +// rstudio/package-manager#19391. Either way it is a question about members +// within a group, never about whether the group itself may be empty. func parseGroup(vv string, sanitizer func(string) string, c conf) ([]Specifier, error) { + if strings.TrimSpace(vv) == "" { + return nil, fmt.Errorf("improper constraint: empty constraint group") + } if !validConstraintRegexp.MatchString(vv) { return nil, fmt.Errorf("improper constraint: %s", vv) } found := specifierRegexp.FindAllString(vv, -1) if found == nil { - if strings.TrimSpace(vv) == "" { - // The universal set. Not an error, and NOT a floor of zero. - return nil, nil - } found = append(found, strings.TrimSpace(vv)) } @@ -458,6 +540,15 @@ func (ss Specifiers) Len() int { // List returns the individual specifiers, flattened across OR-groups in input // order. It is the iteration upstream gets from `iter(SpecifierSet)`. +// +// ⚠️ List is for ITERATION, not for SEMANTICS. It discards the OR-of-ANDs +// structure, so `">=1||<2"` and `">=1,<2"` flatten to the same two members +// while meaning opposite things: the first admits every version, the second +// admits only their intersection. Anything that decides whether two sets are +// the same, or what a set matches, must walk the groups instead — see +// orGroups, Equal and matchAll. Deciding a predicate from a flattened List is +// how Equal came to report `">=1||<2"` equal to `">=1,<2"`, and how And came +// to collapse `(A||B) AND C` into `A AND B AND C`. func (ss Specifiers) List() []Specifier { out := make([]Specifier, 0, ss.Len()) for _, group := range ss.specifiers { diff --git a/version/specifier_query.go b/version/specifier_query.go index a4a2d21..c68e8aa 100644 --- a/version/specifier_query.go +++ b/version/specifier_query.go @@ -13,6 +13,7 @@ package version import ( "errors" + "slices" "strings" ) @@ -216,12 +217,22 @@ func (ss Specifiers) FilterVersions(items []Version, opts ...FilterOption) []Ver return filterGeneric(ss, items, Version.String, opts) } -// Equal reports whether two sets hold the same specifiers, compared -// canonically and irrespective of order, duplicates, or pre-release policy. -// It is upstream's SpecifierSet.__eq__. +// Equal reports whether two sets are the same constraint, compared +// canonically: insensitive to the order of the OR-groups, to the order and +// duplication of members within a group, to trailing zeros and letter case in +// an operand, and to the pre-release policy. It is upstream's +// SpecifierSet.__eq__, extended to this type's OR-of-ANDs shape. +// +// ⚠️ It is NOT insensitive to which members share a group, because that is what +// the constraint IS. `">=1||<2"` admits every version and `">=1,<2"` admits +// only their intersection, so they must not compare equal even though they hold +// the same two members. An earlier version compared a flattened List and did +// report them equal — a wrong equality is especially costly, because it makes +// whatever is built on top of it (dedupe, caches, guards, tests that use it as +// an oracle) silently wrong while Equal's own tests still pass. func (ss Specifiers) Equal(other Specifiers) bool { - left := canonicalKeys(ss) - right := canonicalKeys(other) + left := canonicalGroupKeys(ss) + right := canonicalGroupKeys(other) if len(left) != len(right) { return false } @@ -233,19 +244,63 @@ func (ss Specifiers) Equal(other Specifiers) bool { return true } -// canonicalKeys is the deduplicated set of canonical specifier renderings, -// which is what makes Equal blind to order and duplicates. -func canonicalKeys(ss Specifiers) map[string]struct{} { - keys := make(map[string]struct{}, ss.Len()) - for _, s := range ss.List() { - op, operand := s.canonicalSpec() - keys[op+operand] = struct{}{} +// canonicalGroupKeys returns one key per AND-group: the group's canonicalized +// members, deduplicated and sorted, joined with ",". The result is a SET of +// group keys, so comparison is blind to group order and to within-group order +// and duplicates, while conjunction boundaries survive. +// +// For a set with a single group — everything a Python-style comma-separated +// string produces, and so everything the upstream conformance tables exercise — +// this reduces exactly to the deduplicated, sorted member set. +func canonicalGroupKeys(ss Specifiers) map[string]struct{} { + groups := ss.orGroups() + keys := make(map[string]struct{}, len(groups)) + for _, group := range groups { + members := make([]string, 0, len(group)) + seen := make(map[string]struct{}, len(group)) + for _, s := range group { + op, operand := s.canonicalSpec() + key := op + operand + if _, dup := seen[key]; dup { + continue + } + seen[key] = struct{}{} + members = append(members, key) + } + slices.Sort(members) + keys[strings.Join(members, ",")] = struct{}{} } return keys } -// And returns the intersection of two specifier sets: every specifier from -// both, which is upstream's `SpecifierSet.__and__`. +// orGroups returns the AND-groups, normalizing a set with no groups at all (the +// zero value) to a single EMPTY group. +// +// Those two spellings mean the same thing — a set that constrains nothing, see +// Check — and normalizing here keeps every group-walking operation from having +// to special-case the zero value. It also makes the universal set the identity +// of And, which it must be: `universal AND X` is `X`, and a cartesian product +// against zero groups would instead have produced zero groups. +func (ss Specifiers) orGroups() [][]Specifier { + if len(ss.specifiers) == 0 { + return [][]Specifier{nil} + } + return ss.specifiers +} + +// And returns the intersection of two specifier sets, which is upstream's +// `SpecifierSet.__and__`. +// +// ⚠️ Because this type is an OR of ANDs, intersection DISTRIBUTES; it is not a +// concatenation. `(A||B) AND (C||D)` is `(A,C) || (A,D) || (B,C) || (B,D)`. +// Concatenating the members instead produced `A AND B AND C AND D`, which is a +// strictly narrower and usually unsatisfiable constraint: `(==1.0||==2.0) AND +// <3.0` became `==1.0,==2.0,<3.0` and matched nothing at all, rejecting the two +// versions it should have admitted. +// +// Upstream never has more than one group, so for two Python-style sets this +// collapses to the single concatenated group upstream produces, duplicates +// included. // // The pre-release policies are combined rather than dropped. PreReleasesAuto // on one side yields to the other; two identical explicit policies survive; @@ -257,15 +312,28 @@ func (ss Specifiers) And(other Specifiers) (Specifiers, error) { return Specifiers{}, err } - combined := append(ss.List(), other.List()...) - // Re-stamp each member with the combined policy so a specifier read back - // off the result answers PreReleases consistently with the set. - for i := range combined { - combined[i].pre = pre + left := ss.orGroups() + right := other.orGroups() + + groups := make([][]Specifier, 0, len(left)*len(right)) + for _, l := range left { + for _, r := range right { + group := make([]Specifier, 0, len(l)+len(r)) + group = append(group, l...) + group = append(group, r...) + // Re-stamp each member with the combined policy so a specifier read + // back off the result answers PreReleases consistently with the + // set. The append above copied the values, so this cannot reach + // back into either operand. + for i := range group { + group[i].pre = pre + } + groups = append(groups, group) + } } return Specifiers{ - specifiers: [][]Specifier{combined}, + specifiers: groups, conf: conf{preReleases: pre}, }, nil } From 015553d628e8ffba5d36de535cee24079702a4e6 Mon Sep 17 00:00:00 2001 From: Jonathan Yoder Date: Mon, 10 Aug 2026 13:19:50 -0400 Subject: [PATCH 3/7] A member's policy is the member's; harden ~=; drop a tautological test MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Six review findings. Four are behavioral, two are claims that were wrong. FINDING 1 -- ~= panicked on a suffix-only operand. specifierCompatible derives its prefix by taking release components up to the first post/dev suffix and dropping the last one. An operand that IS a suffix from its first segment ("dev1", "post1", "dev", "post") leaves prefixElements empty, and [:len-1] of empty is [:-1]: "slice bounds out of range". Guarded. ⚠️ The hardening test could not have caught this. Its operand list ("lolwat", "", "not a version", "1.2.3.4.5-garbage") contains no member that reaches the break-on-first-iteration path, so it exercised every operator EXCEPT the one that could crash, while its name and header claimed the whole shape class. The suffix-only shapes are now in the list, plus a dedicated test naming this as the one panic in the table that is a slice bound rather than a MustParse. FINDINGS 6 and 7 -- container state was overwriting member state. newSpecifier stamped the SET's policy onto every member, so a member read off a set reported the set's policy rather than its own: upstream's list(SpecifierSet(">=1.0.dev1", prereleases=False))[0].prereleases is True while the set's is False. And re-stamped members with the combined policy, which could ERASE an explicit member policy and let autodetection reach the opposite answer -- a member built with Exclude on ">=1.0.dev1" became Auto, autodetected Include off the .dev1, and flipped the set's resolved policy, so the combined set offered a pre-release the original held back. NewSpecifiersFrom stamped too, discarding exactly the per-member policy that constructor exists to carry through. parseGroup now takes no conf at all; newSpecifier is reached with a real conf only from NewSpecifier, where the conf IS that specifier's own. This is the same defect shape as the flat-bag bug in e93e425: state that belongs to the member, taken over by the container. Audited every other site and recorded the clean ones in member_policy_test.go -- cmpkey's k.pre, normalizeLocal, filterGeneric's strs[i], every keep[i] mask write, dedupeSpecifiers, orGroups, String/Len/List/Equal/PreReleases, and marker.Environment.With. After this change exactly one line in non-test code sets a member's policy from a conf. FINDING 8 -- the zero-value Specifier was inconsistent. Contains("1.0") was true via Check's nil guard while Contains("lolwat") was false, even though NewSpecifiers("").Contains("lolwat") is true. Three spellings of "no constraint" now agree. The guard is on the nil operator function, not the empty operator string: a parsed bare version has an empty operator and must keep constraining. FINDING 2 -- And now deduplicates, and a false parity claim is removed. The claim that len(SpecifierSet(">=1.0") & SpecifierSet(">=1.0")) == 2 is deliberate upstream parity was wrong. It holds only on a fresh object: len is 2, then str() is ">=1.0", then len is 1, because _canonical_specs() dedupes lazily. So the 2 was a transient artifact of upstream's caching -- the one thing this port declares non-portable -- and it made the count depend on call order. Dedupe is canonical, so ">=1.0.0" and ">=1" collapse while "~=1.18.0" and "~=1.18" do not. Matching is unaffected; a conjunction is idempotent. FINDING 5 -- TestContainsAgreesWithFilterOfOne was tautological. Contains IS len(Filter([]{item})) > 0, so the test asserted an expression against itself and could not fail for any input; its own comment conceded they "can never disagree". Replaced with a 300-row table whose expected values were measured against packaging 26.2 -- an oracle that is not the implementation. FINDING 3 -- three doc comments asserted ==1.0A1 behavior this package cannot produce, because validConstraintRegexp lacks the (?i) flag and rejects it at parse time. They described upstream in Go method doc comments, where a reader takes them as this API's contract. All three qualified, with the divergence and its issue named. Every behavioral fix verified red-then-green: 10 test functions and 22 subtests fail on e93e425, including the real "slice bounds out of range [:-1]" panic. Refs rstudio/package-manager#19383 Co-Authored-By: Claude Opus 5 (1M context) --- CHANGELOG.md | 51 ++++- version/member_policy_test.go | 312 +++++++++++++++++++++++++++ version/operand_hardening_test.go | 44 +++- version/prerelease_policy_test.go | 346 ++++++++++++++++++++++++++++-- version/specifier.go | 52 ++++- version/specifier_api_test.go | 52 ++++- version/specifier_query.go | 109 ++++++++-- 7 files changed, 904 insertions(+), 62 deletions(-) create mode 100644 version/member_policy_test.go diff --git a/CHANGELOG.md b/CHANGELOG.md index 9ae41da..f189094 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -94,11 +94,31 @@ mistaken for a safe patch upgrade. - `Specifiers.Len()`, `Specifiers.List()`, `Specifiers.Equal()`, `Specifiers.And()`, `Specifiers.ContainsInstalled()` and `NewSpecifiersFrom()`. - `And` combines the two sets' pre-release policies rather than dropping them, and + `And` combines the two SETS' pre-release policies rather than dropping them, and returns `ErrPreReleaseConflict` when they contradict (one `Include`, one `Exclude`), - where upstream raises `ValueError`. Like upstream it keeps duplicates — - `len(SpecifierSet(">=1.0") & SpecifierSet(">=1.0"))` is 2 in packaging 26.2 — while - `Equal` is blind to order and duplicates. + where upstream raises `ValueError`. `Equal` is blind to order and duplicates. + + `And` **deduplicates** its members: `NewSpecifiers(">=1.0").And(NewSpecifiers(">=1.0"))` + has `Len()` 1 and renders `">=1.0"`. Deduplication is canonical rather than textual, so + `">=1.0.0"` and `">=1"` also collapse, while `"~=1.18.0"` and `"~=1.18"` do not (their + trailing zero changes which versions they accept). + + ⚠️ **A previous draft of this entry claimed `len(... & ...) == 2` as deliberate upstream + parity. That claim was wrong and has been removed.** It is true only of a *fresh* + upstream object: `packaging` 26.2 deduplicates lazily in `_canonical_specs()`, so + `len(c)` is 2, then `str(c)` is `">=1.0"`, and `len(c)` is then **1**. The 2 was a + transient pre-canonicalization artifact of upstream's caching — the very thing this + port declares non-portable — and it made the count depend on which method a caller + happened to invoke first. Matching was never affected either way, since a conjunction + is idempotent; this is purely about what `Len` and `String` report. + + ⚠️ **Member pre-release policies are left alone.** `And` and `NewSpecifiersFrom` set + only the *set's* policy, matching upstream, whose `__and__` never touches a member's + `_prereleases`. An earlier draft re-stamped every member with the combined policy, + which could **erase** a member's explicit policy and then let autodetection reach the + opposite answer: a member built with `PreReleasesExclude` on the operand `>=1.0.dev1` + became `Auto`, autodetected `Include` off the `.dev1`, and flipped the whole set's + resolved policy — so the combined set offered a pre-release the original had held back. ⚠️ **`And` and `Equal` respect this type's OR-of-ANDs shape**, which upstream has no equivalent of (the `||` operator is this package's extension for the R constraint @@ -113,6 +133,29 @@ mistaken for a safe patch upgrade. cannot be used to decide what a set matches or whether two sets are the same. Its doc comment says so. `Len()` likewise counts members across all groups. + A member read off a set via `List()` reports **its own** pre-release policy, not the + set's, matching upstream: `list(SpecifierSet(">=1.0.dev1", prereleases=False))[0].prereleases` + is `True` in `packaging` 26.2 while the set's is `False`. An earlier draft stamped the + set's policy onto every member at parse time, so the two were indistinguishable. + +- The **zero-value `Specifier`** constrains nothing, consistently. Previously + `Specifier{}.Contains("1.0")` was true while `Specifier{}.Contains("lolwat")` was false, + even though `NewSpecifiers("").Contains("lolwat")` is true — three spellings of "no + constraint" disagreeing on one input class. All three now agree. + +- **`~=` no longer panics on an operand that is entirely a post/dev suffix.** + `specifierCompatible` derives its prefix by taking release components up to the first + suffix and dropping the last one; an operand such as `dev1` or `post1` leaves nothing to + drop, and the slice was `[:-1]` — `slice bounds out of range`. + + ⚠️ Not reachable through the public API (the grammar validates a `~=` operand), but it + was reachable from inside the package and therefore from any new caller, which is what + the exported `Specifier` and `Filter` are. Worth recording separately from the + `MustParse` hardening below because the *test* for that hardening did not cover it: its + operand list (`"lolwat"`, `""`, `"not a version"`, `"1.2.3.4.5-garbage"`) contains no + member that triggers this line, so it exercised every operator except the one that could + crash. The operand list now includes the suffix-only shapes. + - `marker.Environment.With(map[string]string)`, `Environment.Lookup(name)` and `marker.VariableNames()`: the override seam a **partial** marker environment needs. diff --git a/version/member_policy_test.go b/version/member_policy_test.go new file mode 100644 index 0000000..a3d0b6f --- /dev/null +++ b/version/member_policy_test.go @@ -0,0 +1,312 @@ +// SPDX-License-Identifier: Apache-2.0 OR MIT + +// Regression tests for one theme with three symptoms: a member's pre-release +// policy belongs to the MEMBER, and a container must not overwrite it. +// +// newSpecifier stamped the SET's policy onto every member, so a member read +// back off a set reported the set's policy instead of its own. +// And re-stamped members with the combined policy, which could ERASE an +// explicit member policy and let autodetection reach the opposite +// answer -- flipping the whole set's resolved policy. +// NewSpecifiersFrom stamped too, discarding exactly the per-member policy that +// constructor exists to carry through. +// +// This is the same defect shape as the flat-bag bug in or_group_structure_test.go +// -- state that belongs to the member being taken over by the container -- which +// is why the container->member audit below is part of this file. +// +// Upstream is the reference: SpecifierSet keeps its own _prereleases and never +// touches its members'. Verified against pypa/packaging 26.2 throughout. + +package version + +import ( + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// FINDING 7. A member read off a set reports ITS OWN policy. +// +// Measured against packaging 26.2: +// +// ss = SpecifierSet(">=1.0.dev1", prereleases=False) +// ss.prereleases -> False (the set's own) +// list(ss)[0].prereleases -> True (the member's autodetect off ".dev1") +// +// This matters concretely, not just theoretically: List() is documented as +// upstream's `iter(SpecifierSet)` and the ported conformance tables iterate it. +func TestMemberReportsItsOwnPolicyNotTheSets(t *testing.T) { + // wantSet is the set's RESOLVED policy, which is not simply the policy it was + // given: with Auto the set resolves through its members, so a member that + // autodetects Include makes the set Include. Measured against packaging 26.2: + // + // SpecifierSet('>=1.0.dev1', prereleases=None).prereleases -> True + // SpecifierSet('>=1.0.dev1', prereleases=True).prereleases -> True + // SpecifierSet('>=1.0.dev1', prereleases=False).prereleases -> False + // + // The member is True in all three. + cases := []struct { + setPolicy PreReleases + wantSet PreReleases + }{ + {PreReleasesAuto, PreReleasesInclude}, + {PreReleasesInclude, PreReleasesInclude}, + {PreReleasesExclude, PreReleasesExclude}, + } + + for _, tc := range cases { + setPolicy := tc.setPolicy + t.Run("set="+setPolicy.String(), func(t *testing.T) { + ss, err := NewSpecifiers(">=1.0.dev1", WithPreReleases(setPolicy)) + require.NoError(t, err) + + assert.Equal(t, tc.wantSet, ss.PreReleases(), "the set's resolved policy") + + // The member autodetects from its operand, regardless. + require.Len(t, ss.List(), 1) + assert.Equal(t, PreReleasesInclude, ss.List()[0].PreReleases(), + "the member autodetects Include off .dev1, whatever the set says") + + // And it agrees with the same specifier built standalone, which is + // the invariant that makes List() usable at all. + standalone, err := NewSpecifier(">=1.0.dev1") + require.NoError(t, err) + assert.Equal(t, standalone.PreReleases(), ss.List()[0].PreReleases(), + "a member off a set must match the same specifier built alone") + }) + } +} + +// The same for a member with no pre-release in its operand, so the test cannot +// pass merely because Include happens to be the answer everywhere. +func TestMemberAutodetectIsNotOverriddenByAnExplicitSetPolicy(t *testing.T) { + ss, err := NewSpecifiers(">=1.0", WithPreReleases(PreReleasesInclude)) + require.NoError(t, err) + + assert.Equal(t, PreReleasesInclude, ss.PreReleases(), "set") + assert.Equal(t, PreReleasesExclude, ss.List()[0].PreReleases(), + `>=1.0 autodetects Exclude; upstream's Specifier(">=1.0").prereleases is False`) +} + +// A policy passed to NewSpecifier (the SINGULAR constructor) is that +// specifier's own, so it must still stick. This is the boundary of the fix: the +// distinction is set-policy vs member-policy, not "never stamp". +func TestSingularConstructorPolicyStillSticks(t *testing.T) { + for _, policy := range []PreReleases{PreReleasesInclude, PreReleasesExclude} { + s, err := NewSpecifier(">=1.0.dev1", WithPreReleases(policy)) + require.NoError(t, err) + assert.Equal(t, policy, s.PreReleases(), "policy %s", policy) + } +} + +// FINDING 6. And must not re-stamp member policies. +// +// The reproduction is specific: a member carrying an explicit Exclude, in a set +// whose own policy is unset, combined with a plain set. Re-stamping wrote the +// combined policy (Auto) over the member's Exclude; the member then autodetected +// Include off its ".dev1" operand; and the set's resolved policy went from Auto +// to Include, so the combined set offered a pre-release the original held back. +func TestAndDoesNotRestampMemberPolicies(t *testing.T) { + excluded, err := NewSpecifier(">=1.0.dev1", WithPreReleases(PreReleasesExclude)) + require.NoError(t, err) + withExplicitMember := NewSpecifiersFrom([]Specifier{excluded}) + plain, err := NewSpecifiers("<2.0") + require.NoError(t, err) + + // Baseline: the member's explicit Exclude keeps the set from resolving to + // Include. + require.Equal(t, PreReleasesExclude, withExplicitMember.List()[0].PreReleases()) + require.Equal(t, PreReleasesAuto, withExplicitMember.PreReleases()) + + combined, err := withExplicitMember.And(plain) + require.NoError(t, err) + + assert.Equal(t, PreReleasesExclude, combined.List()[0].PreReleases(), + "And must not erase the member's explicit policy") + assert.Equal(t, PreReleasesAuto, combined.PreReleases(), + "and so the set's resolved policy must not flip to Include") +} + +// And must not mutate its operands at all -- the property the re-stamp violated. +func TestAndDoesNotMutateItsOperands(t *testing.T) { + excluded, err := NewSpecifier(">=1.0.dev1", WithPreReleases(PreReleasesExclude)) + require.NoError(t, err) + left := NewSpecifiersFrom([]Specifier{excluded}) + right, err := NewSpecifiers("<2.0", WithPreReleases(PreReleasesInclude)) + require.NoError(t, err) + + leftBefore := left.List()[0].PreReleases() + rightBefore := right.List()[0].PreReleases() + leftStr, rightStr := left.String(), right.String() + + _, err = left.And(right) + require.NoError(t, err) + + assert.Equal(t, leftBefore, left.List()[0].PreReleases(), "left member unchanged") + assert.Equal(t, rightBefore, right.List()[0].PreReleases(), "right member unchanged") + assert.Equal(t, leftStr, left.String(), "left rendering unchanged") + assert.Equal(t, rightStr, right.String(), "right rendering unchanged") +} + +// FINDING 6, second half. NewSpecifiersFrom carries per-member policies through +// rather than overwriting them -- which is the whole reason to accept +// already-parsed specifiers. +func TestNewSpecifiersFromPreservesMemberPolicies(t *testing.T) { + incl, err := NewSpecifier(">=1.0", WithPreReleases(PreReleasesInclude)) + require.NoError(t, err) + excl, err := NewSpecifier("<2.0.dev1", WithPreReleases(PreReleasesExclude)) + require.NoError(t, err) + + // A set-level policy is the SET's, and must not reach the members. + ss := NewSpecifiersFrom([]Specifier{incl, excl}, WithPreReleases(PreReleasesExclude)) + + assert.Equal(t, PreReleasesExclude, ss.PreReleases(), "the set's own policy") + require.Len(t, ss.List(), 2) + assert.Equal(t, PreReleasesInclude, ss.List()[0].PreReleases(), "member 0 keeps Include") + assert.Equal(t, PreReleasesExclude, ss.List()[1].PreReleases(), "member 1 keeps Exclude") +} + +// FINDING 8. The zero-value Specifier constrains nothing, consistently. +// +// Before the fix the two readings disagreed on exactly one input class: +// Contains("1.0") was true via Check's nil guard, while Contains("lolwat") was +// false because the unparseable branch admits a non-version only for "===". +// Meanwhile NewSpecifiers("").Contains("lolwat") is true. Three spellings of +// "no constraint" have to agree. +func TestZeroValueSpecifierConstrainsNothingConsistently(t *testing.T) { + var zero Specifier + + items := []string{"1.0", "0", "2.0a1", "1!3.0", "1.0+local", "lolwat", "not a version", ""} + + for _, item := range items { + assert.True(t, zero.Contains(item), "zero Specifier must admit %q", item) + } + + // Filter keeps everything, in order. + assert.Equal(t, items, zero.Filter(items)) + + // And it agrees with the other two spellings of "no constraint". + emptySet, err := NewSpecifiers("") + require.NoError(t, err) + zeroSet := Specifiers{} + for _, item := range items { + assert.Equal(t, emptySet.Contains(item), zero.Contains(item), + `zero Specifier and NewSpecifiers("") must agree on %q`, item) + assert.Equal(t, emptySet.Contains(item), zeroSet.Contains(item), + `zero Specifiers and NewSpecifiers("") must agree on %q`, item) + } + + // Check already agreed and must keep agreeing. + assert.True(t, zero.Check(MustParse("1.0"))) +} + +// A REAL specifier must not be caught by the zero-value shortcut. The guard is +// on the nil operator function, and a parsed bare version has an empty operator +// string but a non-nil function -- so gating on the operator string instead +// would have turned every bare-version constraint into a no-op. +func TestZeroValueShortcutDoesNotSwallowRealSpecifiers(t *testing.T) { + bare, err := NewSpecifier("2.0") + require.NoError(t, err) + assert.Equal(t, "", bare.Operator(), "a bare version has an empty operator") + assert.True(t, bare.Contains("2.0")) + assert.False(t, bare.Contains("3.0"), "a bare version still constrains") + assert.False(t, bare.Contains("lolwat"), "and still rejects a non-version") + + normal, err := NewSpecifier(">=2.0") + require.NoError(t, err) + assert.False(t, normal.Contains("1.0")) + assert.False(t, normal.Contains("lolwat")) +} + +// CONTAINER -> MEMBER STAMPING AUDIT. +// +// The theme above is container state overwriting member state. This pins the +// invariant directly, for every constructor that produces a set, so a future +// change that reintroduces a stamp fails here rather than in a subtle +// policy-resolution assertion. +// +// Sites checked and found CLEAN, recorded so the audit is legible rather than +// merely asserted: +// +// version.go cmpkey (k.pre = part.Infinity / NegativeInfinity) +// writes the comparison KEY's pre field from the version's OWN +// pre segment. Not container state, and not a Specifier. +// version.go normalizeLocal (segments[i] = ...) +// rewrites the version's own local label in place. Clean. +// filterGeneric (strs[i] = key(it)) +// derives a string from the caller's item via the caller's key +// function; touches no Specifier. Clean. +// filterKeep / Specifiers.filterKeep / matchAll / groupMatches / +// allArbitraryMatch / applyPEP440Preference +// every write is to the boolean result mask. All read-only over +// members. Clean. +// dedupeSpecifiers +// copies member VALUES into a fresh slice and writes no field. +// Clean. +// orGroups +// returns the existing groups or a synthetic empty one; no +// mutation. Clean. +// String / Len / List / Equal / canonicalGroupKeys / PreReleases +// read-only. Clean. +// marker.Environment.With +// copies the receiver and writes only the named fields on the +// COPY; already covered by TestWithDoesNotMutateReceiver. Clean. +// +// After the fix, `newSpecifier` is the ONLY place a member's policy is set from +// a conf, and it is reached with a real conf only from NewSpecifier, where the +// conf is that specifier's own. +func TestNoConstructorStampsMemberPolicyFromSetPolicy(t *testing.T) { + // A pre-release operand so that Auto autodetects Include, and a plain one so + // that Auto autodetects Exclude. If a set policy leaked onto the members, + // one of the two would report the set's value instead. + const preOperand = ">=1.0.dev1" + const finalOperand = ">=1.0" + + for _, setPolicy := range []PreReleases{PreReleasesAuto, PreReleasesInclude, PreReleasesExclude} { + t.Run("NewSpecifiers__"+setPolicy.String(), func(t *testing.T) { + ss, err := NewSpecifiers(preOperand+","+finalOperand, WithPreReleases(setPolicy)) + require.NoError(t, err) + require.Len(t, ss.List(), 2) + assert.Equal(t, PreReleasesInclude, ss.List()[0].PreReleases(), preOperand) + assert.Equal(t, PreReleasesExclude, ss.List()[1].PreReleases(), finalOperand) + }) + + t.Run("NewRSpecifiers__"+setPolicy.String(), func(t *testing.T) { + rs, err := NewRSpecifiers(preOperand+","+finalOperand, identitySanitizer, + WithPreReleases(setPolicy)) + require.NoError(t, err) + require.Len(t, rs.List(), 2) + assert.Equal(t, PreReleasesInclude, rs.List()[0].PreReleases(), preOperand) + assert.Equal(t, PreReleasesExclude, rs.List()[1].PreReleases(), finalOperand) + }) + + t.Run("NewSpecifiersWithSanitizer__"+setPolicy.String(), func(t *testing.T) { + ws, err := NewSpecifiersWithSanitizer(preOperand+","+finalOperand, identitySanitizer, + WithPreReleases(setPolicy)) + require.NoError(t, err) + require.Len(t, ws.List(), 2) + assert.Equal(t, PreReleasesInclude, ws.List()[0].PreReleases(), preOperand) + assert.Equal(t, PreReleasesExclude, ws.List()[1].PreReleases(), finalOperand) + }) + + t.Run("OR_groups__"+setPolicy.String(), func(t *testing.T) { + or, err := NewSpecifiers(preOperand+"||"+finalOperand, WithPreReleases(setPolicy)) + require.NoError(t, err) + require.Len(t, or.List(), 2) + assert.Equal(t, PreReleasesInclude, or.List()[0].PreReleases()) + assert.Equal(t, PreReleasesExclude, or.List()[1].PreReleases()) + }) + + // And the deprecated two-state option must not stamp either. + t.Run("WithPreRelease__"+setPolicy.String(), func(t *testing.T) { + legacy, err := NewSpecifiers(preOperand+","+finalOperand, + WithPreRelease(setPolicy == PreReleasesInclude)) + require.NoError(t, err) + require.Len(t, legacy.List(), 2) + assert.Equal(t, PreReleasesInclude, legacy.List()[0].PreReleases()) + assert.Equal(t, PreReleasesExclude, legacy.List()[1].PreReleases()) + }) + } +} diff --git a/version/operand_hardening_test.go b/version/operand_hardening_test.go index 13acb80..be284b0 100644 --- a/version/operand_hardening_test.go +++ b/version/operand_hardening_test.go @@ -47,7 +47,20 @@ func TestUnparseableOperandDoesNotPanic(t *testing.T) { prospective := MustParse("1.2.3") for _, shape := range operandPanicShapes() { - for _, operand := range []string{"lolwat", "", "not a version", "1.2.3.4.5-garbage"} { + // ⚠️ The last four are load-bearing and were MISSING. + // + // specifierCompatible panics only when the operand's first dot-segment + // starts with "post" or "dev", because that breaks its prefix loop on + // iteration one and leaves an empty slice to be sliced [:len-1]. + // "lolwat", "", "not a version" and "1.2.3.4.5-garbage" all produce a + // non-empty first segment and pass through harmlessly -- so a table + // stocked only with those exercised every operator EXCEPT the one that + // could actually crash, while this test's name and header claimed the + // whole shape class. Verified: adding "dev1" made this test fail. + for _, operand := range []string{ + "lolwat", "", "not a version", "1.2.3.4.5-garbage", + "dev1", "post1", "dev", "post", + } { t.Run(shape.name+"__"+operand, func(t *testing.T) { s := Specifier{op: shape.op, operand: operand, fn: shape.fn} assert.NotPanics(t, func() { @@ -74,10 +87,33 @@ func TestUnparseableOperandDoesNotPanic(t *testing.T) { // bad operand would arrive by. func TestFilterWithUnparseableOperandDoesNotPanic(t *testing.T) { for _, shape := range operandPanicShapes() { - t.Run(shape.name, func(t *testing.T) { - s := Specifier{op: shape.op, operand: "lolwat", fn: shape.fn} + for _, operand := range []string{"lolwat", "dev1", "post1"} { + t.Run(shape.name+"__"+operand, func(t *testing.T) { + s := Specifier{op: shape.op, operand: operand, fn: shape.fn} + assert.NotPanics(t, func() { + s.Filter([]string{"1.0", "2.0a1", "also not a version"}) + }) + }) + } + } +} + +// The compatible operator's own panic shape, called out separately because it is +// the only one in the table that is NOT about MustParse: it is a slice bound. +// +// `~=` derives its prefix by taking release components up to the first +// post/dev suffix and dropping the last one. An operand that IS a suffix from +// its first segment leaves nothing to drop, and `[:len(empty)-1]` is `[:-1]`. +func TestCompatibleOperatorWithSuffixOnlyOperandDoesNotPanic(t *testing.T) { + for _, operand := range []string{"dev1", "post1", "dev", "post", "dev0", "post99"} { + t.Run(operand, func(t *testing.T) { + s := Specifier{op: "~=", operand: operand, fn: specifierCompatible} + assert.NotPanics(t, func() { + assert.False(t, s.Check(MustParse("1.2.3")), + "an operand that is not a version cannot be satisfied") + }) assert.NotPanics(t, func() { - s.Filter([]string{"1.0", "2.0a1", "also not a version"}) + assert.Empty(t, s.Filter([]string{"1.2.3", "0.1"})) }) }) } diff --git a/version/prerelease_policy_test.go b/version/prerelease_policy_test.go index 75cf920..c080bcc 100644 --- a/version/prerelease_policy_test.go +++ b/version/prerelease_policy_test.go @@ -414,22 +414,29 @@ func TestSpecifiers_ContainsInstalled(t *testing.T) { } } -// Contains is defined as "Filter of one item is non-empty", exactly as -// upstream defines it, so the two can never disagree. Cross-check it. -func TestContainsAgreesWithFilterOfOne(t *testing.T) { - specs := []string{"", ">=1.0", "<2", "==2.0.*", "!=1.5", "~=1.4", ">=1.0.dev1", "===lolwat"} - items := []string{"1.0", "1.5", "2.0", "1.5a1", "2.0.dev1", "lolwat", "not a version"} - - for _, spec := range specs { - for _, policy := range []PreReleases{PreReleasesAuto, PreReleasesInclude, PreReleasesExclude} { - ss, err := NewSpecifiers(spec, WithPreReleases(policy)) +// TestContainsMatchesTheReference drives Contains against an INDEPENDENT oracle: +// 300 (specifier, policy, item) combinations whose expected values were measured +// against pypa/packaging 26.2. +// +// ⚠️ This replaces a test called TestContainsAgreesWithFilterOfOne, which was +// TAUTOLOGICAL and could not fail for any input. Contains IS +// `len(Filter([]string{item})) > 0` -- that is its implementation -- and the +// test asserted that expression against itself. It was billed as a cross-check +// and its comment even conceded the two "can never disagree", which should have +// been the tell: a check whose two sides are the same expression measures +// nothing. A real cross-check needs an oracle that is not the implementation. +// +// The Contains/Filter consistency the old test was reaching for is now a +// property of the code rather than of a test: Contains has no logic of its own, +// it delegates. What is worth testing is whether the delegation gives the +// answers the reference gives, which is what this does. +func TestContainsMatchesTheReference(t *testing.T) { + for _, tt := range containsOracle { + t.Run(fmt.Sprintf("%q__%s__%q", tt.spec, tt.policy, tt.item), func(t *testing.T) { + ss, err := NewSpecifiers(tt.spec, WithPreReleases(tt.policy)) require.NoError(t, err) - for _, item := range items { - want := len(ss.Filter([]string{item})) > 0 - assert.Equal(t, want, ss.Contains(item), - "spec=%q policy=%s item=%q", spec, policy, item) - } - } + assert.Equal(t, tt.want, ss.Contains(tt.item)) + }) } } @@ -439,3 +446,312 @@ func emptyToNil(s []string) []string { } return s } + +// 300 rows, expected values measured against pypa/packaging 26.2. +var containsOracle = []struct { + spec string + policy PreReleases + item string + want bool +}{ + {"", PreReleasesAuto, "1.0", true}, + {"", PreReleasesAuto, "1.5", true}, + {"", PreReleasesAuto, "2.0", true}, + {"", PreReleasesAuto, "1.5a1", true}, + {"", PreReleasesAuto, "2.0.dev1", true}, + {"", PreReleasesAuto, "lolwat", true}, + {"", PreReleasesAuto, "not a version", true}, + {"", PreReleasesAuto, "0.5", true}, + {"", PreReleasesAuto, "1.4.9", true}, + {"", PreReleasesAuto, "1!1.0", true}, + {"", PreReleasesInclude, "1.0", true}, + {"", PreReleasesInclude, "1.5", true}, + {"", PreReleasesInclude, "2.0", true}, + {"", PreReleasesInclude, "1.5a1", true}, + {"", PreReleasesInclude, "2.0.dev1", true}, + {"", PreReleasesInclude, "lolwat", true}, + {"", PreReleasesInclude, "not a version", true}, + {"", PreReleasesInclude, "0.5", true}, + {"", PreReleasesInclude, "1.4.9", true}, + {"", PreReleasesInclude, "1!1.0", true}, + {"", PreReleasesExclude, "1.0", true}, + {"", PreReleasesExclude, "1.5", true}, + {"", PreReleasesExclude, "2.0", true}, + {"", PreReleasesExclude, "1.5a1", false}, + {"", PreReleasesExclude, "2.0.dev1", false}, + {"", PreReleasesExclude, "lolwat", true}, + {"", PreReleasesExclude, "not a version", true}, + {"", PreReleasesExclude, "0.5", true}, + {"", PreReleasesExclude, "1.4.9", true}, + {"", PreReleasesExclude, "1!1.0", true}, + {">=1.0", PreReleasesAuto, "1.0", true}, + {">=1.0", PreReleasesAuto, "1.5", true}, + {">=1.0", PreReleasesAuto, "2.0", true}, + {">=1.0", PreReleasesAuto, "1.5a1", true}, + {">=1.0", PreReleasesAuto, "2.0.dev1", true}, + {">=1.0", PreReleasesAuto, "lolwat", false}, + {">=1.0", PreReleasesAuto, "not a version", false}, + {">=1.0", PreReleasesAuto, "0.5", false}, + {">=1.0", PreReleasesAuto, "1.4.9", true}, + {">=1.0", PreReleasesAuto, "1!1.0", true}, + {">=1.0", PreReleasesInclude, "1.0", true}, + {">=1.0", PreReleasesInclude, "1.5", true}, + {">=1.0", PreReleasesInclude, "2.0", true}, + {">=1.0", PreReleasesInclude, "1.5a1", true}, + {">=1.0", PreReleasesInclude, "2.0.dev1", true}, + {">=1.0", PreReleasesInclude, "lolwat", false}, + {">=1.0", PreReleasesInclude, "not a version", false}, + {">=1.0", PreReleasesInclude, "0.5", false}, + {">=1.0", PreReleasesInclude, "1.4.9", true}, + {">=1.0", PreReleasesInclude, "1!1.0", true}, + {">=1.0", PreReleasesExclude, "1.0", true}, + {">=1.0", PreReleasesExclude, "1.5", true}, + {">=1.0", PreReleasesExclude, "2.0", true}, + {">=1.0", PreReleasesExclude, "1.5a1", false}, + {">=1.0", PreReleasesExclude, "2.0.dev1", false}, + {">=1.0", PreReleasesExclude, "lolwat", false}, + {">=1.0", PreReleasesExclude, "not a version", false}, + {">=1.0", PreReleasesExclude, "0.5", false}, + {">=1.0", PreReleasesExclude, "1.4.9", true}, + {">=1.0", PreReleasesExclude, "1!1.0", true}, + {"<2", PreReleasesAuto, "1.0", true}, + {"<2", PreReleasesAuto, "1.5", true}, + {"<2", PreReleasesAuto, "2.0", false}, + {"<2", PreReleasesAuto, "1.5a1", true}, + {"<2", PreReleasesAuto, "2.0.dev1", false}, + {"<2", PreReleasesAuto, "lolwat", false}, + {"<2", PreReleasesAuto, "not a version", false}, + {"<2", PreReleasesAuto, "0.5", true}, + {"<2", PreReleasesAuto, "1.4.9", true}, + {"<2", PreReleasesAuto, "1!1.0", false}, + {"<2", PreReleasesInclude, "1.0", true}, + {"<2", PreReleasesInclude, "1.5", true}, + {"<2", PreReleasesInclude, "2.0", false}, + {"<2", PreReleasesInclude, "1.5a1", true}, + {"<2", PreReleasesInclude, "2.0.dev1", false}, + {"<2", PreReleasesInclude, "lolwat", false}, + {"<2", PreReleasesInclude, "not a version", false}, + {"<2", PreReleasesInclude, "0.5", true}, + {"<2", PreReleasesInclude, "1.4.9", true}, + {"<2", PreReleasesInclude, "1!1.0", false}, + {"<2", PreReleasesExclude, "1.0", true}, + {"<2", PreReleasesExclude, "1.5", true}, + {"<2", PreReleasesExclude, "2.0", false}, + {"<2", PreReleasesExclude, "1.5a1", false}, + {"<2", PreReleasesExclude, "2.0.dev1", false}, + {"<2", PreReleasesExclude, "lolwat", false}, + {"<2", PreReleasesExclude, "not a version", false}, + {"<2", PreReleasesExclude, "0.5", true}, + {"<2", PreReleasesExclude, "1.4.9", true}, + {"<2", PreReleasesExclude, "1!1.0", false}, + {"==2.0.*", PreReleasesAuto, "1.0", false}, + {"==2.0.*", PreReleasesAuto, "1.5", false}, + {"==2.0.*", PreReleasesAuto, "2.0", true}, + {"==2.0.*", PreReleasesAuto, "1.5a1", false}, + {"==2.0.*", PreReleasesAuto, "2.0.dev1", true}, + {"==2.0.*", PreReleasesAuto, "lolwat", false}, + {"==2.0.*", PreReleasesAuto, "not a version", false}, + {"==2.0.*", PreReleasesAuto, "0.5", false}, + {"==2.0.*", PreReleasesAuto, "1.4.9", false}, + {"==2.0.*", PreReleasesAuto, "1!1.0", false}, + {"==2.0.*", PreReleasesInclude, "1.0", false}, + {"==2.0.*", PreReleasesInclude, "1.5", false}, + {"==2.0.*", PreReleasesInclude, "2.0", true}, + {"==2.0.*", PreReleasesInclude, "1.5a1", false}, + {"==2.0.*", PreReleasesInclude, "2.0.dev1", true}, + {"==2.0.*", PreReleasesInclude, "lolwat", false}, + {"==2.0.*", PreReleasesInclude, "not a version", false}, + {"==2.0.*", PreReleasesInclude, "0.5", false}, + {"==2.0.*", PreReleasesInclude, "1.4.9", false}, + {"==2.0.*", PreReleasesInclude, "1!1.0", false}, + {"==2.0.*", PreReleasesExclude, "1.0", false}, + {"==2.0.*", PreReleasesExclude, "1.5", false}, + {"==2.0.*", PreReleasesExclude, "2.0", true}, + {"==2.0.*", PreReleasesExclude, "1.5a1", false}, + {"==2.0.*", PreReleasesExclude, "2.0.dev1", false}, + {"==2.0.*", PreReleasesExclude, "lolwat", false}, + {"==2.0.*", PreReleasesExclude, "not a version", false}, + {"==2.0.*", PreReleasesExclude, "0.5", false}, + {"==2.0.*", PreReleasesExclude, "1.4.9", false}, + {"==2.0.*", PreReleasesExclude, "1!1.0", false}, + {"!=1.5", PreReleasesAuto, "1.0", true}, + {"!=1.5", PreReleasesAuto, "1.5", false}, + {"!=1.5", PreReleasesAuto, "2.0", true}, + {"!=1.5", PreReleasesAuto, "1.5a1", true}, + {"!=1.5", PreReleasesAuto, "2.0.dev1", true}, + {"!=1.5", PreReleasesAuto, "lolwat", false}, + {"!=1.5", PreReleasesAuto, "not a version", false}, + {"!=1.5", PreReleasesAuto, "0.5", true}, + {"!=1.5", PreReleasesAuto, "1.4.9", true}, + {"!=1.5", PreReleasesAuto, "1!1.0", true}, + {"!=1.5", PreReleasesInclude, "1.0", true}, + {"!=1.5", PreReleasesInclude, "1.5", false}, + {"!=1.5", PreReleasesInclude, "2.0", true}, + {"!=1.5", PreReleasesInclude, "1.5a1", true}, + {"!=1.5", PreReleasesInclude, "2.0.dev1", true}, + {"!=1.5", PreReleasesInclude, "lolwat", false}, + {"!=1.5", PreReleasesInclude, "not a version", false}, + {"!=1.5", PreReleasesInclude, "0.5", true}, + {"!=1.5", PreReleasesInclude, "1.4.9", true}, + {"!=1.5", PreReleasesInclude, "1!1.0", true}, + {"!=1.5", PreReleasesExclude, "1.0", true}, + {"!=1.5", PreReleasesExclude, "1.5", false}, + {"!=1.5", PreReleasesExclude, "2.0", true}, + {"!=1.5", PreReleasesExclude, "1.5a1", false}, + {"!=1.5", PreReleasesExclude, "2.0.dev1", false}, + {"!=1.5", PreReleasesExclude, "lolwat", false}, + {"!=1.5", PreReleasesExclude, "not a version", false}, + {"!=1.5", PreReleasesExclude, "0.5", true}, + {"!=1.5", PreReleasesExclude, "1.4.9", true}, + {"!=1.5", PreReleasesExclude, "1!1.0", true}, + {"~=1.4", PreReleasesAuto, "1.0", false}, + {"~=1.4", PreReleasesAuto, "1.5", true}, + {"~=1.4", PreReleasesAuto, "2.0", false}, + {"~=1.4", PreReleasesAuto, "1.5a1", true}, + {"~=1.4", PreReleasesAuto, "2.0.dev1", false}, + {"~=1.4", PreReleasesAuto, "lolwat", false}, + {"~=1.4", PreReleasesAuto, "not a version", false}, + {"~=1.4", PreReleasesAuto, "0.5", false}, + {"~=1.4", PreReleasesAuto, "1.4.9", true}, + {"~=1.4", PreReleasesAuto, "1!1.0", false}, + {"~=1.4", PreReleasesInclude, "1.0", false}, + {"~=1.4", PreReleasesInclude, "1.5", true}, + {"~=1.4", PreReleasesInclude, "2.0", false}, + {"~=1.4", PreReleasesInclude, "1.5a1", true}, + {"~=1.4", PreReleasesInclude, "2.0.dev1", false}, + {"~=1.4", PreReleasesInclude, "lolwat", false}, + {"~=1.4", PreReleasesInclude, "not a version", false}, + {"~=1.4", PreReleasesInclude, "0.5", false}, + {"~=1.4", PreReleasesInclude, "1.4.9", true}, + {"~=1.4", PreReleasesInclude, "1!1.0", false}, + {"~=1.4", PreReleasesExclude, "1.0", false}, + {"~=1.4", PreReleasesExclude, "1.5", true}, + {"~=1.4", PreReleasesExclude, "2.0", false}, + {"~=1.4", PreReleasesExclude, "1.5a1", false}, + {"~=1.4", PreReleasesExclude, "2.0.dev1", false}, + {"~=1.4", PreReleasesExclude, "lolwat", false}, + {"~=1.4", PreReleasesExclude, "not a version", false}, + {"~=1.4", PreReleasesExclude, "0.5", false}, + {"~=1.4", PreReleasesExclude, "1.4.9", true}, + {"~=1.4", PreReleasesExclude, "1!1.0", false}, + {">=1.0.dev1", PreReleasesAuto, "1.0", true}, + {">=1.0.dev1", PreReleasesAuto, "1.5", true}, + {">=1.0.dev1", PreReleasesAuto, "2.0", true}, + {">=1.0.dev1", PreReleasesAuto, "1.5a1", true}, + {">=1.0.dev1", PreReleasesAuto, "2.0.dev1", true}, + {">=1.0.dev1", PreReleasesAuto, "lolwat", false}, + {">=1.0.dev1", PreReleasesAuto, "not a version", false}, + {">=1.0.dev1", PreReleasesAuto, "0.5", false}, + {">=1.0.dev1", PreReleasesAuto, "1.4.9", true}, + {">=1.0.dev1", PreReleasesAuto, "1!1.0", true}, + {">=1.0.dev1", PreReleasesInclude, "1.0", true}, + {">=1.0.dev1", PreReleasesInclude, "1.5", true}, + {">=1.0.dev1", PreReleasesInclude, "2.0", true}, + {">=1.0.dev1", PreReleasesInclude, "1.5a1", true}, + {">=1.0.dev1", PreReleasesInclude, "2.0.dev1", true}, + {">=1.0.dev1", PreReleasesInclude, "lolwat", false}, + {">=1.0.dev1", PreReleasesInclude, "not a version", false}, + {">=1.0.dev1", PreReleasesInclude, "0.5", false}, + {">=1.0.dev1", PreReleasesInclude, "1.4.9", true}, + {">=1.0.dev1", PreReleasesInclude, "1!1.0", true}, + {">=1.0.dev1", PreReleasesExclude, "1.0", true}, + {">=1.0.dev1", PreReleasesExclude, "1.5", true}, + {">=1.0.dev1", PreReleasesExclude, "2.0", true}, + {">=1.0.dev1", PreReleasesExclude, "1.5a1", false}, + {">=1.0.dev1", PreReleasesExclude, "2.0.dev1", false}, + {">=1.0.dev1", PreReleasesExclude, "lolwat", false}, + {">=1.0.dev1", PreReleasesExclude, "not a version", false}, + {">=1.0.dev1", PreReleasesExclude, "0.5", false}, + {">=1.0.dev1", PreReleasesExclude, "1.4.9", true}, + {">=1.0.dev1", PreReleasesExclude, "1!1.0", true}, + {"===lolwat", PreReleasesAuto, "1.0", false}, + {"===lolwat", PreReleasesAuto, "1.5", false}, + {"===lolwat", PreReleasesAuto, "2.0", false}, + {"===lolwat", PreReleasesAuto, "1.5a1", false}, + {"===lolwat", PreReleasesAuto, "2.0.dev1", false}, + {"===lolwat", PreReleasesAuto, "lolwat", true}, + {"===lolwat", PreReleasesAuto, "not a version", false}, + {"===lolwat", PreReleasesAuto, "0.5", false}, + {"===lolwat", PreReleasesAuto, "1.4.9", false}, + {"===lolwat", PreReleasesAuto, "1!1.0", false}, + {"===lolwat", PreReleasesInclude, "1.0", false}, + {"===lolwat", PreReleasesInclude, "1.5", false}, + {"===lolwat", PreReleasesInclude, "2.0", false}, + {"===lolwat", PreReleasesInclude, "1.5a1", false}, + {"===lolwat", PreReleasesInclude, "2.0.dev1", false}, + {"===lolwat", PreReleasesInclude, "lolwat", true}, + {"===lolwat", PreReleasesInclude, "not a version", false}, + {"===lolwat", PreReleasesInclude, "0.5", false}, + {"===lolwat", PreReleasesInclude, "1.4.9", false}, + {"===lolwat", PreReleasesInclude, "1!1.0", false}, + {"===lolwat", PreReleasesExclude, "1.0", false}, + {"===lolwat", PreReleasesExclude, "1.5", false}, + {"===lolwat", PreReleasesExclude, "2.0", false}, + {"===lolwat", PreReleasesExclude, "1.5a1", false}, + {"===lolwat", PreReleasesExclude, "2.0.dev1", false}, + {"===lolwat", PreReleasesExclude, "lolwat", true}, + {"===lolwat", PreReleasesExclude, "not a version", false}, + {"===lolwat", PreReleasesExclude, "0.5", false}, + {"===lolwat", PreReleasesExclude, "1.4.9", false}, + {"===lolwat", PreReleasesExclude, "1!1.0", false}, + {">=1.0,<2.0", PreReleasesAuto, "1.0", true}, + {">=1.0,<2.0", PreReleasesAuto, "1.5", true}, + {">=1.0,<2.0", PreReleasesAuto, "2.0", false}, + {">=1.0,<2.0", PreReleasesAuto, "1.5a1", true}, + {">=1.0,<2.0", PreReleasesAuto, "2.0.dev1", false}, + {">=1.0,<2.0", PreReleasesAuto, "lolwat", false}, + {">=1.0,<2.0", PreReleasesAuto, "not a version", false}, + {">=1.0,<2.0", PreReleasesAuto, "0.5", false}, + {">=1.0,<2.0", PreReleasesAuto, "1.4.9", true}, + {">=1.0,<2.0", PreReleasesAuto, "1!1.0", false}, + {">=1.0,<2.0", PreReleasesInclude, "1.0", true}, + {">=1.0,<2.0", PreReleasesInclude, "1.5", true}, + {">=1.0,<2.0", PreReleasesInclude, "2.0", false}, + {">=1.0,<2.0", PreReleasesInclude, "1.5a1", true}, + {">=1.0,<2.0", PreReleasesInclude, "2.0.dev1", false}, + {">=1.0,<2.0", PreReleasesInclude, "lolwat", false}, + {">=1.0,<2.0", PreReleasesInclude, "not a version", false}, + {">=1.0,<2.0", PreReleasesInclude, "0.5", false}, + {">=1.0,<2.0", PreReleasesInclude, "1.4.9", true}, + {">=1.0,<2.0", PreReleasesInclude, "1!1.0", false}, + {">=1.0,<2.0", PreReleasesExclude, "1.0", true}, + {">=1.0,<2.0", PreReleasesExclude, "1.5", true}, + {">=1.0,<2.0", PreReleasesExclude, "2.0", false}, + {">=1.0,<2.0", PreReleasesExclude, "1.5a1", false}, + {">=1.0,<2.0", PreReleasesExclude, "2.0.dev1", false}, + {">=1.0,<2.0", PreReleasesExclude, "lolwat", false}, + {">=1.0,<2.0", PreReleasesExclude, "not a version", false}, + {">=1.0,<2.0", PreReleasesExclude, "0.5", false}, + {">=1.0,<2.0", PreReleasesExclude, "1.4.9", true}, + {">=1.0,<2.0", PreReleasesExclude, "1!1.0", false}, + {"!=1.0,>=0.5", PreReleasesAuto, "1.0", false}, + {"!=1.0,>=0.5", PreReleasesAuto, "1.5", true}, + {"!=1.0,>=0.5", PreReleasesAuto, "2.0", true}, + {"!=1.0,>=0.5", PreReleasesAuto, "1.5a1", true}, + {"!=1.0,>=0.5", PreReleasesAuto, "2.0.dev1", true}, + {"!=1.0,>=0.5", PreReleasesAuto, "lolwat", false}, + {"!=1.0,>=0.5", PreReleasesAuto, "not a version", false}, + {"!=1.0,>=0.5", PreReleasesAuto, "0.5", true}, + {"!=1.0,>=0.5", PreReleasesAuto, "1.4.9", true}, + {"!=1.0,>=0.5", PreReleasesAuto, "1!1.0", true}, + {"!=1.0,>=0.5", PreReleasesInclude, "1.0", false}, + {"!=1.0,>=0.5", PreReleasesInclude, "1.5", true}, + {"!=1.0,>=0.5", PreReleasesInclude, "2.0", true}, + {"!=1.0,>=0.5", PreReleasesInclude, "1.5a1", true}, + {"!=1.0,>=0.5", PreReleasesInclude, "2.0.dev1", true}, + {"!=1.0,>=0.5", PreReleasesInclude, "lolwat", false}, + {"!=1.0,>=0.5", PreReleasesInclude, "not a version", false}, + {"!=1.0,>=0.5", PreReleasesInclude, "0.5", true}, + {"!=1.0,>=0.5", PreReleasesInclude, "1.4.9", true}, + {"!=1.0,>=0.5", PreReleasesInclude, "1!1.0", true}, + {"!=1.0,>=0.5", PreReleasesExclude, "1.0", false}, + {"!=1.0,>=0.5", PreReleasesExclude, "1.5", true}, + {"!=1.0,>=0.5", PreReleasesExclude, "2.0", true}, + {"!=1.0,>=0.5", PreReleasesExclude, "1.5a1", false}, + {"!=1.0,>=0.5", PreReleasesExclude, "2.0.dev1", false}, + {"!=1.0,>=0.5", PreReleasesExclude, "lolwat", false}, + {"!=1.0,>=0.5", PreReleasesExclude, "not a version", false}, + {"!=1.0,>=0.5", PreReleasesExclude, "0.5", true}, + {"!=1.0,>=0.5", PreReleasesExclude, "1.4.9", true}, + {"!=1.0,>=0.5", PreReleasesExclude, "1!1.0", true}, +} diff --git a/version/specifier.go b/version/specifier.go index 05b5cc8..4fa8e90 100644 --- a/version/specifier.go +++ b/version/specifier.go @@ -135,9 +135,14 @@ type Specifier struct { // validConstraintRegexp comment in init). op string // operand is the right-hand side with surrounding whitespace removed and - // the sanitizer applied. It is NOT normalized as a version: upstream's - // Specifier.version returns the operand as written, so `==1.0A1` keeps - // its upper-case spelling. Verified against pypa/packaging 26.2. + // the sanitizer applied. It is NOT normalized as a version: like upstream's + // Specifier.version it is the operand as written, so `>= v1.0 ` keeps its + // "v" prefix. + // + // ⚠️ Upstream also preserves an upper-case spelling (`==1.0A1` keeps + // `1.0A1`), but this package cannot reach that case: validConstraintRegexp + // lacks the (?i) flag specifierRegexp has, so `==1.0A1` is rejected at + // parse time. Tracked in rstudio/package-manager#19391. operand string // original is the specifier as matched in the input, whitespace and all. original string @@ -189,7 +194,7 @@ func newRSpecifiers(v string, sanitizer func(string) string, opts ...SpecifierOp } vv = strings.ReplaceAll(vv, "-", ".") - specs, err := parseGroup(vv, sanitizer, *c) + specs, err := parseGroup(vv, sanitizer) if err != nil { return Specifiers{}, err } @@ -226,7 +231,7 @@ func newSpecifiers(v string, sanitizer func(string) string, opts ...SpecifierOpt vv = ">=0.0.0" } - specs, err := parseGroup(vv, sanitizer, *c) + specs, err := parseGroup(vv, sanitizer) if err != nil { return Specifiers{}, err } @@ -341,7 +346,15 @@ func NewSpecifier(s string, opts ...SpecifierOption) (Specifier, error) { // validConstraintRegexp, and that remaining divergence is tracked in // rstudio/package-manager#19391. Either way it is a question about members // within a group, never about whether the group itself may be empty. -func parseGroup(vv string, sanitizer func(string) string, c conf) ([]Specifier, error) { +// ⚠️ parseGroup deliberately takes no conf. The pre-release policy passed to +// NewSpecifiers belongs to the SET, not to its members, and stamping it onto +// each member conflates the two: upstream's SpecifierSet keeps its own +// _prereleases and leaves every member's alone, so +// `list(SpecifierSet(">=1.0.dev1", prereleases=False))[0].prereleases` is True +// (the member's own autodetect) while the set's is False. Members are built +// with the zero policy and autodetect individually; the set's policy is applied +// at query time from ss.conf. +func parseGroup(vv string, sanitizer func(string) string) ([]Specifier, error) { if strings.TrimSpace(vv) == "" { return nil, fmt.Errorf("improper constraint: empty constraint group") } @@ -356,7 +369,7 @@ func parseGroup(vv string, sanitizer func(string) string, c conf) ([]Specifier, specs := make([]Specifier, 0, len(found)) for _, single := range found { - s, err := newSpecifier(single, sanitizer, c) + s, err := newSpecifier(single, sanitizer, conf{}) if err != nil { return nil, err } @@ -486,9 +499,14 @@ func (s Specifier) Check(v Version) bool { func (s Specifier) Operator() string { return s.op } // Version returns the specifier's operand as written, with surrounding -// whitespace removed: `Specifier("== 1.0A1").Version()` is "1.0A1", not -// "1.0a1". Upstream does the same — the operand is normalized when it is -// compared, not when it is stored. +// whitespace removed: `NewSpecifier(">= v1.0 ").Version()` is "v1.0", not +// "1.0". Like upstream, the operand is normalized when it is compared, not when +// it is stored. +// +// ⚠️ Upstream demonstrates this with case as well (`Specifier("== 1.0A1").version` +// is `1.0A1`). That example does not work here: `==1.0A1` is rejected at parse +// time because validConstraintRegexp lacks the (?i) flag. See +// rstudio/package-manager#19391. func (s Specifier) Version() string { return s.operand } // Original returns the specifier exactly as it appeared in the input, @@ -656,6 +674,20 @@ func specifierCompatible(prospective Version, spec string) bool { prefixElements = append(prefixElements, s) } + // ⚠️ An operand whose FIRST dot-segment already starts with "post" or "dev" + // breaks the loop on iteration one, leaving prefixElements empty -- and + // slicing [:len-1] of an empty slice panics with "slice bounds out of range + // [:-1]". Reachable with the operand "dev1", "post1", "dev" or "post". + // + // This is the same landmine class as the MustParse sites, and note which + // operands DO NOT trigger it: "lolwat", "", "not a version" and "1.2.3.4.5-garbage" + // all pass through harmlessly, because they produce a non-empty first + // segment. A hardening test stocked only with those shapes therefore proves + // nothing about this line, which is exactly how it was missed. + if len(prefixElements) == 0 { + return false + } + // We want everything but the last item in the version, but we want to ignore post and dev releases, and // we want to treat the pre-release as its own separate segment. prefix := strings.Join(prefixElements[:len(prefixElements)-1], ".") diff --git a/version/specifier_api_test.go b/version/specifier_api_test.go index 7bed143..66ac50a 100644 --- a/version/specifier_api_test.go +++ b/version/specifier_api_test.go @@ -200,18 +200,58 @@ func TestSpecifiers_And(t *testing.T) { assert.False(t, combined.Check(MustParse("3.0"))) } -// ⚠️ And keeps duplicates rather than deduplicating, matching upstream: -// len(SpecifierSet(">=1.0") & SpecifierSet(">=1.0")) is 2 in packaging 26.2, -// even though its str() renders the deduplicated ">=1.0". Equal is the -// operation that is blind to duplicates. -func TestSpecifiers_And_KeepsDuplicatesButEqualIgnoresThem(t *testing.T) { +// And deduplicates, which is where upstream SETTLES even though a fresh object +// reports otherwise. +// +// ⚠️ Measured against packaging 26.2, `len(SpecifierSet(">=1.0") & +// SpecifierSet(">=1.0"))` is 2 on a fresh object, 1 after any canonicalizing +// call, and `str()` is ">=1.0" always: +// +// c = SpecifierSet(">=1.0") & SpecifierSet(">=1.0") +// len(c) -> 2 +// str(c) -> '>=1.0' +// len(c) -> 1 # _canonical_specs() dedupes LAZILY +// +// So the 2 is an artifact of upstream's lazy cache -- the very thing this port +// declares non-portable -- and it makes the count depend on call order. An +// earlier version of this test asserted the 2 and cited it as deliberate +// upstream parity, which was wrong on both counts. +// +// Matching is unaffected either way: a conjunction is idempotent. +func TestSpecifiers_And_Deduplicates(t *testing.T) { one, err := NewSpecifiers(">=1.0") require.NoError(t, err) combined, err := one.And(one) require.NoError(t, err) - assert.Equal(t, 2, combined.Len()) + assert.Equal(t, 1, combined.Len(), "a repeated member collapses") + assert.Equal(t, ">=1.0", combined.String()) assert.True(t, combined.Equal(one)) + + // Matching is the same either way, which is why this is safe. + assert.True(t, combined.Check(MustParse("1.5"))) + assert.False(t, combined.Check(MustParse("0.5"))) + + // Deduplication is CANONICAL, not textual: these are the same constraint. + a, err := NewSpecifiers(">=1.0.0") + require.NoError(t, err) + b, err := NewSpecifiers(">=1") + require.NoError(t, err) + collapsed, err := a.And(b) + require.NoError(t, err) + assert.Equal(t, 1, collapsed.Len()) + + // But genuinely distinct members are all kept, including the `~=` pair whose + // trailing zero is load-bearing. + narrow, err := NewSpecifiers("~=1.18.0") + require.NoError(t, err) + wide, err := NewSpecifiers("~=1.18") + require.NoError(t, err) + both, err := narrow.And(wide) + require.NoError(t, err) + assert.Equal(t, 2, both.Len(), "~=1.18.0 and ~=1.18 are different constraints") + assert.False(t, both.Contains("1.19.5")) + assert.True(t, both.Contains("1.18.0")) } func TestSpecifiers_And_PreReleasePolicyCombination(t *testing.T) { diff --git a/version/specifier_query.go b/version/specifier_query.go index c68e8aa..3085b8a 100644 --- a/version/specifier_query.go +++ b/version/specifier_query.go @@ -141,16 +141,22 @@ func (s Specifier) FilterVersions(items []Version, opts ...FilterOption) []Versi // Equal reports whether two specifiers are equal after canonicalization, // matching upstream's Specifier.__eq__. The pre-release policy is ignored, -// trailing zeros in the operand are not significant, and the operand's case -// and `v` prefix are normalized: +// trailing zeros in the operand are not significant, and a `v` prefix, a zero +// epoch and local-segment case are normalized: // // ==2.8.0 == ==2.8 (true) -// ==1.0A1 == ==1.0a1 (true) +// ==v1.0 == ==1.0 (true) +// ==0!1.0 == ==1.0 (true) // ~=1.18.0 == ~=1.18 (FALSE — `~=` keeps trailing zeros, because they // change which versions it matches) // // A `===` operand and a `.*` wildcard are compared verbatim, since neither is // a version that can be canonicalized. +// +// ⚠️ Canonicalization would also make `==1.0A1` equal `==1.0a1`, as it does +// upstream, but neither `==1.0A1` nor `==1.0+ABC` can be built here at all: +// validConstraintRegexp lacks the (?i) flag, so both are rejected at parse +// time. See rstudio/package-manager#19391. func (s Specifier) Equal(other Specifier) bool { lop, lv := s.canonicalSpec() rop, rv := other.canonicalSpec() @@ -302,10 +308,19 @@ func (ss Specifiers) orGroups() [][]Specifier { // collapses to the single concatenated group upstream produces, duplicates // included. // -// The pre-release policies are combined rather than dropped. PreReleasesAuto -// on one side yields to the other; two identical explicit policies survive; -// Include on one side and Exclude on the other is a contradiction and returns -// ErrPreReleaseConflict, as upstream raises ValueError. +// The pre-release policies of the two SETS are combined rather than dropped. +// PreReleasesAuto on one side yields to the other; two identical explicit +// policies survive; Include on one side and Exclude on the other is a +// contradiction and returns ErrPreReleaseConflict, as upstream raises +// ValueError. +// +// ⚠️ Member policies are left alone, as upstream's `__and__` leaves them. An +// earlier version re-stamped every member with the combined policy, which could +// ERASE a member's explicit policy and then let autodetection reach the opposite +// answer: a member built with PreReleasesExclude on the operand `>=1.0.dev1` +// became Auto, autodetected to Include off the `.dev1`, and flipped the whole +// set's resolved policy from Auto to Include -- so the combined set offered a +// pre-release the original had held back. A member's policy is the member's. func (ss Specifiers) And(other Specifiers) (Specifiers, error) { pre, err := combinePreReleases(ss.conf.preReleases, other.conf.preReleases) if err != nil { @@ -318,17 +333,7 @@ func (ss Specifiers) And(other Specifiers) (Specifiers, error) { groups := make([][]Specifier, 0, len(left)*len(right)) for _, l := range left { for _, r := range right { - group := make([]Specifier, 0, len(l)+len(r)) - group = append(group, l...) - group = append(group, r...) - // Re-stamp each member with the combined policy so a specifier read - // back off the result answers PreReleases consistently with the - // set. The append above copied the values, so this cannot reach - // back into either operand. - for i := range group { - group[i].pre = pre - } - groups = append(groups, group) + groups = append(groups, dedupeSpecifiers(l, r)) } } @@ -338,6 +343,47 @@ func (ss Specifiers) And(other Specifiers) (Specifiers, error) { }, nil } +// dedupeSpecifiers concatenates AND-groups, dropping any member whose canonical +// form has already been seen. First-occurrence order is preserved (this package +// does not sort; see Specifiers.String). +// +// ⚠️ Deduplicating is a divergence from a LITERAL reading of upstream, and +// agreement with the settled one. +// +// `len(SpecifierSet(">=1.0") & SpecifierSet(">=1.0"))` really is 2 in packaging +// 26.2 -- but only on a fresh object. Ask for `str()` first and it is 1, and +// asking for `len()` again after `str()` also gives 1, because +// `_canonical_specs()` deduplicates LAZILY and every canonicalizing operation +// triggers it. So 2 is a transient pre-canonicalization artifact of upstream's +// caching, not its answer; `str()` is `">=1.0"` under every ordering. An earlier +// version of this package cited that 2 as deliberate upstream parity, which was +// wrong twice over: it anchored a compatibility claim on the one thing this port +// explicitly declares non-portable (lazy caches), and it made the count depend +// on which method a caller happened to call first. +// +// Matching is unaffected either way, because a conjunction is idempotent -- this +// is purely about what Len and String report. +func dedupeSpecifiers(groups ...[]Specifier) []Specifier { + size := 0 + for _, g := range groups { + size += len(g) + } + out := make([]Specifier, 0, size) + seen := make(map[string]struct{}, size) + for _, g := range groups { + for _, s := range g { + op, operand := s.canonicalSpec() + key := op + operand + if _, dup := seen[key]; dup { + continue + } + seen[key] = struct{}{} + out = append(out, s) + } + } + return out +} + func combinePreReleases(left, right PreReleases) (PreReleases, error) { switch { case left == PreReleasesAuto: @@ -352,6 +398,12 @@ func combinePreReleases(left, right PreReleases) (PreReleases, error) { // NewSpecifiersFrom builds a set from already-parsed specifiers, which is // upstream's `SpecifierSet(iterable_of_Specifier)`. The members are used as // given; no re-parsing happens. +// +// ⚠️ A policy passed here applies to the SET and does not overwrite the members' +// own, matching upstream: `SpecifierSet(iterable, prereleases=X)` sets its own +// `_prereleases` and leaves each member's alone. An earlier version stamped it +// onto every member, which discarded exactly the per-member policy this +// constructor exists to carry through. func NewSpecifiersFrom(specs []Specifier, opts ...SpecifierOption) Specifiers { c := new(conf) for _, o := range opts { @@ -359,11 +411,6 @@ func NewSpecifiersFrom(specs []Specifier, opts ...SpecifierOption) Specifiers { } group := make([]Specifier, len(specs)) copy(group, specs) - if c.preReleases != PreReleasesAuto { - for i := range group { - group[i].pre = c.preReleases - } - } return Specifiers{specifiers: [][]Specifier{group}, conf: *c} } @@ -419,6 +466,22 @@ func filterGeneric[T any](f Filterer, items []T, key func(T) string, opts []Filt func (s Specifier) filterKeep(items []string, fc filterConf) []bool { keep := make([]bool, len(items)) + // A zero-value Specifier has no operator function and constrains nothing, so + // it offers everything -- including a string that is not a PEP 440 version. + // + // ⚠️ Without this, the two readings of "constrains nothing" disagreed on + // exactly one input class: Specifier{}.Contains("1.0") was true (Check's nil + // guard) while Specifier{}.Contains("lolwat") was false, because the + // unparseable branch below admits a non-version only for "===". Meanwhile + // NewSpecifiers("").Contains("lolwat") is true. Three spellings of the same + // idea have to give the same answer. + if s.fn == nil { + for i := range keep { + keep[i] = true + } + return keep + } + // A per-call policy wins over the one the specifier carries; otherwise the // specifier's resolved policy decides. effective := fc.preReleases From bcf0481cac0d5d76406a420eede4cbaf1ea80995 Mon Sep 17 00:00:00 2001 From: Jonathan Yoder Date: Mon, 10 Aug 2026 13:34:59 -0400 Subject: [PATCH 4/7] "Constrains nothing" is about matching, not selection MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit My fix for finding 8 introduced a worse bug than the one it fixed, and it was the selection-versus-matching conflation for the third time in this change's history. The fix short-circuited Specifier.filterKeep on a nil operator function by filling the result with true and returning BEFORE the pre-release logic. Measured on 015553d: zero Specifier Filter(["1.0","1.1a1"]) Auto = [1.0 1.1a1] NewSpecifiers("") same = [1.0] zero Specifier same, WithPreReleases(Exclude) = [1.0 1.1a1] NewSpecifiers("") same = [1.0] So a zero-value Specifier offered a pre-release even though a final release was available -- the rule its own doc comment describes -- and an explicit PreReleasesExclude could no longer exclude anything. "Constrains nothing" is a statement about MATCHING: the operator admits every version. It is not a statement about SELECTION, which is a separate axis that still has to run. The nil operator function is now a flag consumed by the existing loop (via admitsUnparseable, and via Check's existing nil guard on the parseable path) rather than an early return that skips everything downstream. Fixed a fourth spelling in the same family while re-checking the others: allArbitraryMatch re-tested `op == "==="` inline instead of sharing the predicate, so NewSpecifiersFrom([]Specifier{{}}).Contains("lolwat") was false while Specifier{}.Contains("lolwat") was true. Two copies of one predicate is how they drifted; there is now a single admitsUnparseable used by both call sites. Added the companion test whose absence let this through: all four spellings of "constrains nothing" -- zero Specifier, zero Specifiers, NewSpecifiers(""), and a set holding a zero member -- are asserted to agree on Filter output with a pre-release present, with a lone pre-release, and under each explicit policy, as well as on Contains across eight input classes including three unparseable ones. ⚠️ Note for the record: a parsed bare version (NewSpecifier("2.0")) is NOT a spelling of "constrains nothing". It is a real constraint equivalent to ==2.0, and TestZeroValueShortcutDoesNotSwallowRealSpecifiers pins that separately -- the zero-value shortcut keys on the nil operator FUNCTION, not the empty operator string, precisely so a bare version does not become a no-op. Red-then-green: 4 subtests fail on 015553d, reporting "zero Specifier must hold back the pre-release when a final release is available", "zero Specifier must honor PreReleasesExclude", and three "set with zero member must agree on Contains(...)" failures. The lone-pre-release subtest passes both ways and is a guard. Refs rstudio/package-manager#19383 Co-Authored-By: Claude Opus 5 (1M context) --- CHANGELOG.md | 35 +++++++++-- version/member_policy_test.go | 113 ++++++++++++++++++++++++++-------- version/specifier_query.go | 74 +++++++++++++++------- 3 files changed, 169 insertions(+), 53 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index f189094..98da1b9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -138,10 +138,37 @@ mistaken for a safe patch upgrade. is `True` in `packaging` 26.2 while the set's is `False`. An earlier draft stamped the set's policy onto every member at parse time, so the two were indistinguishable. -- The **zero-value `Specifier`** constrains nothing, consistently. Previously - `Specifier{}.Contains("1.0")` was true while `Specifier{}.Contains("lolwat")` was false, - even though `NewSpecifiers("").Contains("lolwat")` is true — three spellings of "no - constraint" disagreeing on one input class. All three now agree. +- **"Constrains nothing" now means the same thing on both axes.** Four spellings — the + zero-value `Specifier`, the zero-value `Specifiers`, `NewSpecifiers("")`, and a set + holding a zero-value member — agree on matching *and* on pre-release selection. + + Two defects were involved, and the second was introduced by the fix for the first: + + 1. **Matching axis.** `Specifier{}.Contains("1.0")` was true (via `Check`'s nil guard) + while `Specifier{}.Contains("lolwat")` was false, because the unparseable branch + admitted a non-version only for `===`. `NewSpecifiers("").Contains("lolwat")` is + true, so the spellings disagreed on one input class. Additionally + `NewSpecifiersFrom([]Specifier{{}}).Contains("lolwat")` was false, because + `allArbitraryMatch` re-tested `op == "==="` inline instead of sharing the predicate — + two spellings of the same test in two places, which is how they drifted. There is + now one, `admitsUnparseable`. + + 2. ⚠️ **Selection axis.** The first fix short-circuited on a nil operator function by + filling the result with `true` and returning **before** the pre-release logic. That + made `Specifier{}.Filter(["1.0", "1.1a1"])` offer the pre-release *even though a final + release was available*, and made `WithPreReleases(PreReleasesExclude)` silently + unable to exclude anything — an explicit caller override ignored. + + The root cause of the second is worth stating because this change's history hit it three + separate times: **"constrains nothing" is a statement about MATCHING, not about + SELECTION.** The operator admitting every version says nothing about which of the + matching versions are then offered as candidates; that axis still has to run. A nil + operator function is now a flag consumed by the filter loop rather than an early return + that skips everything downstream. + + A companion test asserts all four spellings agree on `Filter` output with a pre-release + present, with a lone pre-release, and under each explicit policy. The absence of exactly + that test is what let the second defect through. - **`~=` no longer panics on an operand that is entirely a post/dev suffix.** `specifierCompatible` derives its prefix by taking release components up to the first diff --git a/version/member_policy_test.go b/version/member_policy_test.go index a3d0b6f..21472ba 100644 --- a/version/member_policy_test.go +++ b/version/member_policy_test.go @@ -168,38 +168,97 @@ func TestNewSpecifiersFromPreservesMemberPolicies(t *testing.T) { assert.Equal(t, PreReleasesExclude, ss.List()[1].PreReleases(), "member 1 keeps Exclude") } -// FINDING 8. The zero-value Specifier constrains nothing, consistently. +// FINDING 8. "Constrains nothing" must mean the same thing everywhere -- on the +// MATCHING axis and on the SELECTION axis, which are separate. // -// Before the fix the two readings disagreed on exactly one input class: -// Contains("1.0") was true via Check's nil guard, while Contains("lolwat") was -// false because the unparseable branch admits a non-version only for "===". -// Meanwhile NewSpecifiers("").Contains("lolwat") is true. Three spellings of -// "no constraint" have to agree. -func TestZeroValueSpecifierConstrainsNothingConsistently(t *testing.T) { - var zero Specifier - - items := []string{"1.0", "0", "2.0a1", "1!3.0", "1.0+local", "lolwat", "not a version", ""} - - for _, item := range items { - assert.True(t, zero.Contains(item), "zero Specifier must admit %q", item) - } - - // Filter keeps everything, in order. - assert.Equal(t, items, zero.Filter(items)) - - // And it agrees with the other two spellings of "no constraint". +// The original defect was on the matching axis: Contains("1.0") was true via +// Check's nil guard while Contains("lolwat") was false, because the unparseable +// branch admitted a non-version only for "===". +// +// ⚠️ The first fix for that introduced a second defect on the SELECTION axis, by +// short-circuiting on a nil operator function and returning before the +// pre-release logic. That made a zero-value Specifier offer a pre-release even +// when a final release was available, and made an explicit PreReleasesExclude +// unable to exclude anything. Both axes are asserted below, because covering +// only the first is what let that through. +// +// Note on what counts as a spelling of "no constraint": the zero-value +// Specifier, the zero-value Specifiers, NewSpecifiers("") and a set holding a +// zero-value member. A parsed bare version (`NewSpecifier("2.0")`) is NOT one of +// them -- it is a real constraint equivalent to ==2.0, and +// TestZeroValueShortcutDoesNotSwallowRealSpecifiers pins that separately. +func TestConstrainsNothingAgreesOnBothAxes(t *testing.T) { emptySet, err := NewSpecifiers("") require.NoError(t, err) - zeroSet := Specifiers{} - for _, item := range items { - assert.Equal(t, emptySet.Contains(item), zero.Contains(item), - `zero Specifier and NewSpecifiers("") must agree on %q`, item) - assert.Equal(t, emptySet.Contains(item), zeroSet.Contains(item), - `zero Specifiers and NewSpecifiers("") must agree on %q`, item) + + // The four spellings, as a common Filterer so one loop covers them all. + spellings := map[string]Filterer{ + "zero Specifier": Specifier{}, + "zero Specifiers": Specifiers{}, + `NewSpecifiers("")`: emptySet, + "set with zero member": NewSpecifiersFrom([]Specifier{{}}), } - // Check already agreed and must keep agreeing. - assert.True(t, zero.Check(MustParse("1.0"))) + t.Run("matching axis: every item is admitted", func(t *testing.T) { + items := []string{"1.0", "0", "1!3.0", "1.0+local", "lolwat", "not a version", ""} + for name, f := range spellings { + got := filterGeneric(f, items, func(s string) string { return s }, nil) + assert.Equal(t, items, got, "%s must admit every item", name) + } + }) + + t.Run("selection axis: a final release is preferred", func(t *testing.T) { + // A pre-release alongside a final must be held back -- the rule the + // short-circuit skipped. + items := []string{"1.0", "1.1a1"} + for name, f := range spellings { + got := filterGeneric(f, items, func(s string) string { return s }, nil) + assert.Equal(t, []string{"1.0"}, got, + "%s must hold back the pre-release when a final release is available", name) + } + }) + + t.Run("selection axis: a lone pre-release is offered", func(t *testing.T) { + items := []string{"1.1a1"} + for name, f := range spellings { + got := filterGeneric(f, items, func(s string) string { return s }, nil) + assert.Equal(t, items, got, "%s must offer a lone pre-release", name) + } + }) + + t.Run("selection axis: an explicit policy is honored", func(t *testing.T) { + items := []string{"1.0", "1.1a1"} + for name, f := range spellings { + excl := filterGeneric(f, items, func(s string) string { return s }, + []FilterOption{WithPreReleases(PreReleasesExclude)}) + assert.Equal(t, []string{"1.0"}, excl, + "%s must honor PreReleasesExclude", name) + + incl := filterGeneric(f, items, func(s string) string { return s }, + []FilterOption{WithPreReleases(PreReleasesInclude)}) + assert.Equal(t, items, incl, "%s must honor PreReleasesInclude", name) + + // And Exclude must be able to empty the result entirely. + lonePre := filterGeneric(f, []string{"1.1a1"}, func(s string) string { return s }, + []FilterOption{WithPreReleases(PreReleasesExclude)}) + assert.Empty(t, lonePre, "%s: PreReleasesExclude must exclude a lone pre-release", name) + } + }) + + t.Run("Contains agrees across all four spellings", func(t *testing.T) { + items := []string{"1.0", "0", "2.0a1", "1!3.0", "1.0+local", "lolwat", "not a version", ""} + for _, item := range items { + want := emptySet.Contains(item) + for name, f := range spellings { + got := len(filterGeneric(f, []string{item}, func(s string) string { return s }, nil)) > 0 + assert.Equal(t, want, got, "%s must agree on Contains(%q)", name, item) + } + } + }) + + // Check is the matching axis on its own, and must keep admitting everything. + assert.True(t, Specifier{}.Check(MustParse("1.0"))) + assert.True(t, Specifier{}.Check(MustParse("1.1a1"))) } // A REAL specifier must not be caught by the zero-value shortcut. The guard is diff --git a/version/specifier_query.go b/version/specifier_query.go index 3085b8a..188d80b 100644 --- a/version/specifier_query.go +++ b/version/specifier_query.go @@ -463,24 +463,43 @@ func filterGeneric[T any](f Filterer, items []T, key func(T) string, opts []Filt // released if nothing was yielded directly — that is the "offer a pre-release // when there is nothing else" rule, and it is why Filter's answer for one // item can differ from its answer for that item alongside a final release. -func (s Specifier) filterKeep(items []string, fc filterConf) []bool { - keep := make([]bool, len(items)) - - // A zero-value Specifier has no operator function and constrains nothing, so - // it offers everything -- including a string that is not a PEP 440 version. - // - // ⚠️ Without this, the two readings of "constrains nothing" disagreed on - // exactly one input class: Specifier{}.Contains("1.0") was true (Check's nil - // guard) while Specifier{}.Contains("lolwat") was false, because the - // unparseable branch below admits a non-version only for "===". Meanwhile - // NewSpecifiers("").Contains("lolwat") is true. Three spellings of the same - // idea have to give the same answer. +// admitsUnparseable reports whether this specifier can match an item that is not +// a valid PEP 440 version. +// +// Two specifiers can: arbitrary equality spelled the same way, and one that +// constrains nothing at all (a zero value, whose operator function is nil). +// Everything else needs a version to compare against and therefore cannot match. +// +// ⚠️ This is the MATCHING axis only. It says the operator admits the item; it +// says nothing about whether the item is then offered as a candidate. For an +// unparseable string the two happen to coincide, because there is no version to +// classify as a pre-release and so the selection rules have nothing to act on -- +// but that coincidence is confined to this one branch and must not be +// generalized. See filterKeep. +func (s Specifier) admitsUnparseable(item string) bool { if s.fn == nil { - for i := range keep { - keep[i] = true - } - return keep + return true } + return s.op == "===" && strings.EqualFold(item, s.operand) +} + +// ⚠️ "Constrains nothing" is a statement about MATCHING, not about SELECTION. +// +// A zero-value Specifier has no operator function, so its operator admits every +// version -- that is the matching axis, and Check's nil guard implements it. The +// pre-release policy is a SEPARATE axis that still has to run: a set that +// constrains nothing still prefers a final release over a pre-release, and still +// honors an explicit PreReleasesExclude. +// +// An earlier version of this function short-circuited on `s.fn == nil` by +// filling keep with true and returning BEFORE the policy logic below. That +// conflated the two axes for the third time in this change's history: it made +// `Specifier{}.Filter(["1.0", "1.1a1"])` offer the pre-release even though a +// final release was available, and made `WithPreReleases(PreReleasesExclude)` +// silently unable to exclude anything. The nil operator function is now a flag +// consumed by the loop (see admitsUnparseable and Check), so both axes run. +func (s Specifier) filterKeep(items []string, fc filterConf) []bool { + keep := make([]bool, len(items)) // A per-call policy wins over the one the specifier carries; otherwise the // specifier's resolved policy decides. @@ -504,11 +523,12 @@ func (s Specifier) filterKeep(items []string, fc filterConf) []bool { for i, item := range items { v, err := Parse(item) if err != nil { - // Not a PEP 440 version. Only arbitrary equality can match it, and - // when it does it is offered unconditionally: there is no way to - // tell whether an opaque token is a pre-release, so the - // pre-release rules do not apply to it at all. - if s.op == "===" && strings.EqualFold(item, s.operand) { + // Not a PEP 440 version. Only arbitrary equality -- or a specifier + // that constrains nothing at all -- can match it, and when one does + // it is offered unconditionally: there is no way to tell whether an + // opaque token is a pre-release, so the pre-release rules have + // nothing to apply to. + if s.admitsUnparseable(item) { keep[i] = true } continue @@ -614,11 +634,21 @@ func groupMatches(group []Specifier, item string, v Version) bool { return true } +// allArbitraryMatch reports whether any AND-group admits an item that is not a +// valid PEP 440 version, which needs EVERY member of that group to admit it. +// +// ⚠️ Uses the same admitsUnparseable predicate as Specifier.filterKeep, rather +// than re-testing `op == "==="` inline. Testing the operator directly made a +// zero-value member -- which constrains nothing and admits everything -- report +// that it did NOT admit an unparseable string, so +// `NewSpecifiersFrom([]Specifier{{}}).Contains("lolwat")` was false while the +// bare `Specifier{}.Contains("lolwat")` was true. Two spellings of the same +// predicate in two places is how they drifted; there is now one. func (ss Specifiers) allArbitraryMatch(item string) bool { for _, group := range ss.specifiers { all := len(group) > 0 for _, s := range group { - if s.op != "===" || !strings.EqualFold(item, s.operand) { + if !s.admitsUnparseable(item) { all = false break } From 244fc46e8a6ed0a1580b746d14b4732bcee9836a Mon Sep 17 00:00:00 2001 From: Jonathan Yoder Date: Mon, 10 Aug 2026 13:45:31 -0400 Subject: [PATCH 5/7] Give NewSpecifier its own grammar instead of borrowing the set's MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit NewSpecifier validated with validConstraintRegexp -- the SET grammar -- which tolerates a trailing comma deliberately. That leniency leaked into the singular constructor: NewSpecifier(">=1,") was accepted and silently yielded the single specifier ">=1", contradicting the function's own doc comment ("A comma-separated set is not a single specifier") and the inline rationale two lines below it. Measured against packaging 26.2, which draws the line sharply: Specifier(">=1,") -> InvalidSpecifier SpecifierSet(">=1,") -> len 1 Specifier(",>=1") -> InvalidSpecifier SpecifierSet(",>=1") -> len 1 Specifier(",") -> InvalidSpecifier SpecifierSet(",") -> len 0 So the doc comment was right and the code was wrong. NewSpecifier now validates against a dedicated anchored single-constraint grammar, so the strictness it promises is delivered on purpose rather than as a side effect of which comma positions the set grammar happens to reject. Same "one rule, one copy" lesson as admitsUnparseable, applied to grammars. ⚠️ Two corrections to the finding as reported. First, only ">=1," was affected, not ",>=1". The set grammar's trailing `,?` admits one trailing comma; a LEADING comma was never in that pattern, so ",>=1" was already rejected by NewSpecifier. Second, and more importantly, this is NOT a side effect of the comma widening in #19391. Verified by running the same probe on this branch, which does not contain that work: NewSpecifier(">=1,") was accepted here too, identically. The defect originates where NewSpecifier was written -- borrowing the plural grammar -- so it belongs in this PR rather than the one that widened the set. The diagnosis of the root cause was exactly right; only the attribution and the affected-input set were narrower. Blast radius: nothing real narrows. TestNewSpecifier_StillAcceptsEveryWell FormedSingle pins 24 well-formed shapes including whitespace forms (">= 1.0", ">= v1.0 ", leading/trailing tabs and newlines), bare versions, epochs, locals, wildcards, arbitrary equality and pre/post/dev operands. A trailing comma on a SINGLE specifier is not a real-world shape -- it only arises from splitting a set, which goes through NewSpecifiers. Red-then-green: TestNewSpecifier_RejectsAnyComma fails on bcf0481 for ">=1," and ">=1 , ", and the set-contrast test fails there too because the two constructors had not yet diverged. Refs rstudio/package-manager#19383 Co-Authored-By: Claude Opus 5 (1M context) --- CHANGELOG.md | 15 +++++++ version/specifier.go | 60 ++++++++++++++++++++++----- version/specifier_api_test.go | 77 +++++++++++++++++++++++++++++++++++ 3 files changed, 141 insertions(+), 11 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 98da1b9..58940ef 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -62,6 +62,21 @@ mistaken for a safe patch upgrade. `Equal` canonicalizes instead: `==2.8.0` equals `==2.8`, but `~=1.18.0` does **not** equal `~=1.18`, because trailing zeros change which versions `~=` accepts. + `NewSpecifier` rejects a **comma in any position** — `">=1,<2"`, `">=1,"`, `",>=1"` + and `","` are all errors — because a comma is set punctuation with no meaning inside + one specifier. Upstream agrees: `Specifier` raises `InvalidSpecifier` for every one of + those while the corresponding `SpecifierSet` calls all succeed. + + ⚠️ It has its own **anchored single-constraint grammar** rather than borrowing the set + grammar. An earlier draft validated with the set grammar, which tolerates a trailing + comma deliberately, so `NewSpecifier(">=1,")` was accepted and silently yielded the + single specifier `>=1` — contradicting this constructor's own documented contract. The + strictness the doc comment promised was being delivered by accident, and only for the + comma positions the set grammar happened to reject. A singular constructor validating + with the plural grammar is a coupling that breaks silently whenever the plural grammar + moves; the two are now independent, with a test asserting the set constructor still + accepts the trailing comma the singular one rejects. + - `PreReleases`, a three-state pre-release policy (`PreReleasesAuto`, `PreReleasesInclude`, `PreReleasesExclude`) with the `WithPreReleases` option, which works both as a `SpecifierOption` at construction and as a `FilterOption` overriding it diff --git a/version/specifier.go b/version/specifier.go index 4fa8e90..9817e5b 100644 --- a/version/specifier.go +++ b/version/specifier.go @@ -25,9 +25,10 @@ var ( "===": specifierArbitrary, } - specifierRegexp *regexp.Regexp - validConstraintRegexp *regexp.Regexp - prefixRegexp *regexp.Regexp + specifierRegexp *regexp.Regexp + validConstraintRegexp *regexp.Regexp + singleConstraintRegexp *regexp.Regexp + prefixRegexp *regexp.Regexp ) // orderedOperatorPatterns returns the regexp-quoted comparison operators in a @@ -112,6 +113,25 @@ func init() { fmt.Sprintf(`^\s*(?:%s\s*(?:,\s*%s\s*)*,?)?\s*$`, constraint, constraint), ) + // EXACTLY ONE constraint, with no comma anywhere: the grammar for the + // SINGULAR NewSpecifier. + // + // ⚠️ This exists because NewSpecifier must NOT borrow the set grammar above. + // The set grammar tolerates a trailing comma on purpose, and that leniency + // leaked straight into the singular constructor: `NewSpecifier(">=1,")` was + // accepted and silently yielded the single specifier `>=1`, contradicting + // NewSpecifier's own documented contract. Upstream draws the line sharply -- + // measured against packaging 26.2, `Specifier(">=1,")`, `Specifier(",>=1")` + // and `Specifier(",")` all raise InvalidSpecifier while the corresponding + // SpecifierSet calls all succeed. + // + // One rule, one copy. A singular constructor validating with the plural + // grammar is a coupling that breaks silently whenever the plural grammar + // moves, which is exactly how this was introduced. + singleConstraintRegexp = regexp.MustCompile( + fmt.Sprintf(`^\s*%s\s*$`, constraint), + ) + prefixRegexp = regexp.MustCompile(`^([0-9]+)((?:a|b|c|rc)[0-9]+)$`) } @@ -298,22 +318,40 @@ func universalSpecifiers(c conf) Specifiers { // NewSpecifier parses a single PEP 440 version specifier, such as `>=1.2.3`. // // It is the singular counterpart to NewSpecifiers and mirrors upstream's -// `Specifier(spec, prereleases=...)` constructor. A comma-separated set is not -// a single specifier: pass those to NewSpecifiers instead. +// `Specifier(spec, prereleases=...)` constructor. +// +// A COMMA is rejected outright, in any position — `">=1,<2"`, `">=1,"`, +// `",>=1"` and `","` are all errors. A comma is set punctuation and has no +// meaning inside one specifier, and upstream agrees: measured against +// packaging 26.2, `Specifier` raises `InvalidSpecifier` for every one of those +// while the corresponding `SpecifierSet` calls all succeed. Pass a set to +// NewSpecifiers instead. +// +// Whitespace is permitted and stripped (`">= 1.0"`, `">= v1.0 "`), and a bare +// version with no operator is accepted as this package's deliberate extension +// for the R path (see the validConstraintRegexp comment in init). func NewSpecifier(s string, opts ...SpecifierOption) (Specifier, error) { c := new(conf) for _, o := range opts { o.apply(c) } - // Reject anything the specifier grammar does not accept in full, so that - // NewSpecifier(">=1,<2") is an error rather than a silent ">=1" with the - // rest dropped on the floor. specifierRegexp is unanchored (Specifiers - // scans with it), so a bare FindStringSubmatch would happily match a - // prefix. - if !validConstraintRegexp.MatchString(s) { + // Validate against the SINGLE-constraint grammar, not the set grammar, so + // that NewSpecifier(">=1,<2") is an error rather than a silent ">=1" with the + // rest dropped on the floor -- and so that a comma is rejected outright + // rather than inherited from the set grammar's deliberate trailing-comma + // leniency. See singleConstraintRegexp. + // + // specifierRegexp is unanchored (Specifiers scans with it), so a bare + // FindStringSubmatch would happily match a prefix; the anchored grammar is + // what makes the whole input have to be one specifier. + if !singleConstraintRegexp.MatchString(s) { return Specifier{}, fmt.Errorf("improper specifier: %s", s) } + // Belt and braces: the anchored grammar already guarantees one constraint, so + // this only fires if the grammar and the scanner ever disagree about where a + // constraint ends. Cheap, and the failure it would catch is a silent wrong + // parse rather than an error. found := specifierRegexp.FindAllString(s, -1) if len(found) != 1 { return Specifier{}, fmt.Errorf("improper specifier: %s", s) diff --git a/version/specifier_api_test.go b/version/specifier_api_test.go index 66ac50a..881cc09 100644 --- a/version/specifier_api_test.go +++ b/version/specifier_api_test.go @@ -74,6 +74,83 @@ func TestNewSpecifier_RejectsASet(t *testing.T) { } } +// A comma has no place in a SINGLE specifier, in any position. +// +// ⚠️ `NewSpecifier(">=1,")` used to be ACCEPTED, silently yielding the single +// specifier `>=1`. The cause was a coupling rather than a typo: NewSpecifier +// validated with validConstraintRegexp, the SET grammar, which tolerates a +// trailing comma deliberately. That leniency is correct for a set and wrong for +// a single specifier, and borrowing the grammar inherited it. NewSpecifier now +// has its own anchored single-constraint grammar. +// +// Upstream draws the same line, measured against packaging 26.2: +// +// Specifier(">=1,") -> InvalidSpecifier SpecifierSet(">=1,") -> len 1 +// Specifier(",>=1") -> InvalidSpecifier SpecifierSet(",>=1") -> len 1 +// Specifier(",") -> InvalidSpecifier SpecifierSet(",") -> len 0 +func TestNewSpecifier_RejectsAnyComma(t *testing.T) { + for _, in := range []string{ + ">=1,", // trailing -- the one that was accepted + ",>=1", // leading + ">=1,,", // trailing doubled + ",,>=1", // leading doubled + ",", // nothing but a comma + ",,", // + ">=1 , ", // trailing with spaces + " , >=1", // leading with spaces + } { + t.Run(fmt.Sprintf("%q", in), func(t *testing.T) { + _, err := NewSpecifier(in) + assert.Error(t, err, "NewSpecifier(%q) must reject a comma", in) + }) + } +} + +// The set constructor must be UNAFFECTED by the singular tightening. This is +// what makes the two grammars genuinely independent rather than one being a +// stricter alias of the other: the trailing comma the set tolerates on purpose +// is still tolerated there, and only the singular constructor rejects it. +// +// ⚠️ Scope note: on this branch the set grammar accepts a TRAILING comma only. +// Leading and doubled commas are a separate widening (upstream drops every blank +// comma item) that lands with the conformance tables in +// rstudio/package-manager#19391, and the fuller contrast table lives there. +func TestNewSpecifiersStillAcceptsTheTrailingCommaTheSingularRejects(t *testing.T) { + for _, in := range []string{">=1,", ">=1 , ", ">= 1.0,"} { + t.Run(fmt.Sprintf("%q", in), func(t *testing.T) { + ss, err := NewSpecifiers(in) + require.NoError(t, err, "the SET grammar must still accept %q", in) + assert.Equal(t, 1, ss.Len()) + + _, err = NewSpecifier(in) + assert.Error(t, err, "the SINGULAR grammar must reject %q", in) + }) + } + + // A comma-separated set is of course still a set. + ss, err := NewSpecifiers(">=1,<2") + require.NoError(t, err) + assert.Equal(t, 2, ss.Len()) +} + +// And the tightening must not narrow any well-formed single specifier. This is +// the "did I break something real" half: every shape here parsed before and must +// still parse. +func TestNewSpecifier_StillAcceptsEveryWellFormedSingle(t *testing.T) { + for _, in := range []string{ + ">=1", ">=1.0", ">= 1.0", "== 1.0", "==1.0", "!=1.0", "<2", "<=2", ">2", + "~=2.0", "==2.1.*", "!=2.2.*", "===lolwat", "===1.0", + ">= v1.0 ", " >=1.0 ", ">=1.0\t", "\t>=1.0\n", + "2.0", "1.2.3", "1!2.0", "1.0+local", // bare versions: this package's extension + ">=1.0.dev1", ">=7.9a1", "<1.0.dev1", ">2.0.post1", + } { + t.Run(fmt.Sprintf("%q", in), func(t *testing.T) { + _, err := NewSpecifier(in) + assert.NoError(t, err, "NewSpecifier(%q) must still be accepted", in) + }) + } +} + func TestNewSpecifier_Invalid(t *testing.T) { for _, in := range []string{"", "=>2.0", "==", "~=1", ">=1.0+deadbeef", "<1.0.*"} { t.Run(fmt.Sprintf("%q", in), func(t *testing.T) { From 28645969f3c554ce21c22e60b9cd77ce43042bc0 Mon Sep 17 00:00:00 2001 From: Jonathan Yoder Date: Mon, 10 Aug 2026 13:59:43 -0400 Subject: [PATCH 6/7] Fix the v0.4.0 padding under-count and the epoch regression it caused MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 🔴 Release-blocking. v0.4.0 answers ==X.*, !=X.* and ~= wrongly, and a repository server built on it SERVES versions pip EXCLUDES. F1 -- padVersion's two zero-padding loops were written `for i := 0; i < len(a)-len(b); i++` while appending to b INSIDE the loop, so the bound was re-evaluated each iteration and shrank as the slice grew. They appended ceil(d/2) zeros for a gap of d segments. ==2.0.0.* did not match 2; !=7.0.0.* DID match 7. F2 -- versionSplit did not prepend the epoch the way upstream's _version_split does, so "1!1.0" split to ["1!1","0"], the digit filter dropped "1!1" entirely, and the under-padding made the two sides coincidentally equal: ==0.0.0.* MATCHED 1!1.0. The retired go-pep440-version said false and packaging 26.2 says False, so this one was introduced by the earlier padVersion change rather than inherited. WHICH FIX IS LOAD-BEARING, measured rather than assumed: fixing the loop bound ALONE takes the 82-row oracle from 30 divergences to 7, and it removes every epoch false-positive -- so the under-padding, not the missing epoch prepend, was the proximate cause of the ==0.0.0.* match. The remaining 7 need the epoch prepend plus suffix-aware padding. Fixed by porting upstream's _version_split / _version_join / _is_not_suffix / _numeric_prefix_len / _left_pad directly, replacing padVersion and isDigist, and rewriting specifierEqual's wildcard branch and specifierCompatible's prefix derivation on top of them. That code already existed on the #19391 branch and is transplanted here verbatim so this PR is correct standalone -- whichever of the two merges first, main is right -- and so the forward-merge is trivial. ⚠️ WHY THIS SURVIVED A REWRITE, A RELEASE AND A CHANGELOG CLAIM: ceil(1/2) == 1, so a gap of ONE segment is padded correctly by accident, and every pre-existing regression case here was a 1-segment gap. v0.4.0's changelog asserted the padding worked "as PEP 440 requires"; that held only for a 1-segment gap. The new table sweeps gaps of 1-4 in both directions, with zero and non-zero tails, pre-release segments and epochs, and every expected value comes from packaging 26.2. Measured on the RELEASED module rather than just the parent commit: v0.4.0 diverges on 30 of the 82 rows, identically to this branch before the fix. 0 after. Blast radius vs v0.4.0 over 28,529 distinct specifier tokens (production PyPI + real CRAN), 24-version panel: parse acceptance ... 0 newly accepted, 0 newly rejected match results ...... 2 tokens change, ==2.0.* and !=2.0.*, both on the version 2rc1, and both move TO packaging's answer (True / False); v0.4.0 had them backwards. Instrument validated: 7 of 8 synthetic multi-segment controls appended to the corpus flip. The 8th needs a panel version the panel lacks and is covered by the oracle instead. The small real count reflects that multi-segment wildcards barely occur in real data, NOT that the bug was harmless -- it is reachable from arbitrary client input. Also corrects a claim this changelog made: the "13 pairs where the old answer agreed with packaging" were described as a separate, pre-existing epoch divergence. They are neither. The old module was correct, the new one was wrong, and the cause was padVersion itself. Red-then-green: 30 of the 82 subtests fail on 244fc46. ⚠️ Do NOT tag from this commit without an explicit decision: v0.4.0 is immutable and already consumed, so shipping this is a Breaking release. Refs rstudio/package-manager#19383, rstudio/package-manager#18634 Co-Authored-By: Claude Opus 5 (1M context) --- CHANGELOG.md | 68 ++++++++++ version/padding_conformance_test.go | 198 ++++++++++++++++++++++++++++ version/specifier.go | 194 ++++++++++++++++++--------- version/specifier_test.go | 94 ++++++++++--- 4 files changed, 476 insertions(+), 78 deletions(-) create mode 100644 version/padding_conformance_test.go diff --git a/CHANGELOG.md b/CHANGELOG.md index 58940ef..fd5898d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,74 @@ mistaken for a safe patch upgrade. ### Breaking +- 🔴 **`v0.4.0` shipped a zero-padding bug that made `==X.*`, `!=X.*` and `~=` answer + wrongly, and a new epoch regression. If you are on `v0.4.0`, upgrade.** + + Two defects, both fixed here. They are stated bluntly because a repository server + built on the broken code **serves versions pip excludes**. + + **The padding bug.** `padVersion`'s two zero-padding loops were written + `for i := 0; i < len(a)-len(b); i++` while *appending to `b` inside the loop*, so the + bound was re-evaluated every iteration and shrank as the slice grew. They appended + **⌈d/2⌉ zeros for a gap of d segments**, not `d`. Traced for a gap of 3: `i=0`, `0<3`, + append (b now 3); `i=1`, `1<2`, append (b now 4); `i=2`, `2<1`, stop — two zeros where + three were needed. + + | specifier | version | `v0.4.0` | `packaging` 26.2 | + |---|---|---|---| + | `==2.0.*` | `2` | true | True ✓ | + | `==2.0.0.*` | `2` | **false** | **True** ✗ | + | `!=7.0.0.*` | `7` | **true** | **False** ✗ | + | `~=2.0.0.0` | `2` | **false** | **True** ✗ | + | `==2.0.0.0.*` | `2` | **false** | **True** ✗ | + + ⚠️ `!=7.0.0.*` matching `7` is the customer-visible one: a server **serves** a version + pip **excludes**. In PPM it is reachable from arbitrary client input on + `POST /__api__/repos/:id/filter/packages`. + + ⚠️ **Why this survived a rewrite, a release, and a changelog claim.** `⌈1/2⌉ == 1`, so a + gap of **one** segment is padded correctly by accident — and every pre-existing + regression case in this area was a 1-segment gap. `v0.4.0`'s changelog asserted the + padding worked "as PEP 440 requires"; **that was true only for a 1-segment gap.** The + new table sweeps gaps of 1–4 in both directions. + + **The epoch regression.** `versionSplit` did not prepend the epoch the way upstream's + `_version_split` does, so `"1!1.0"` split to `["1!1", "0"]`; the digit filter then + dropped `"1!1"` entirely, and the under-padding made the two sides coincidentally equal + — so **`==0.0.0.*` MATCHED `1!1.0`**. The retired `go-pep440-version` answered `false` + here and `packaging` 26.2 answers `False`, so this was a regression *introduced* by the + earlier `padVersion` change, not an inherited defect. + + ⚠️ **This corrects a claim made in this changelog.** The entry below about `padVersion` + described "13 pairs where the old answer agreed with `packaging`" as *"a separate + pre-existing epoch divergence"*. **That framing was wrong**: they are neither separate + nor pre-existing. The old module was correct, the new one was wrong, and the proximate + cause was the very function the release claimed to have fixed. The corrected framing is + in that entry. + + **Which fix is load-bearing, measured rather than assumed:** fixing the padding loop + *alone* takes the 82-row oracle from **30 divergences to 7**, and it removes every epoch + false-positive — so the under-padding, not the missing epoch prepend, was the proximate + cause of `==0.0.0.*` matching `1!1.0`. The remaining 7 need the epoch prepend and + suffix-aware padding. Both loops, the digit filter, and the split are now a direct port + of upstream's `_version_split` / `_numeric_prefix_len` / `_left_pad`, verified at **0 of + 82**. + + **Blast radius, measured against `v0.4.0` itself** over 28,528 distinct specifier tokens + from the production PyPI corpus plus real CRAN constraints (1,926 of them wildcard or + `~=`), across a 24-version panel: + + - parse acceptance: **0 newly accepted, 0 newly rejected** — this is a matching fix; + - match results: **2 tokens change**, `==2.0.*` and `!=2.0.*`, both on the version + `2rc1`. `==2.0.*` now matches it and `!=2.0.*` no longer does, which is what + `packaging` 26.2 answers (`True` / `False`); `v0.4.0` had both backwards. + + Instrument validated: 7 of 8 synthetic multi-segment controls appended to the corpus do + flip. (The 8th, `==1!1.0.0.*`, needs the version `1!1` which the panel does not carry; + it is covered directly by the oracle table.) The small real-world count reflects that + multi-segment-gap wildcards barely occur in real constraint data — **not** that the bug + was harmless, since it is reachable from arbitrary client input. + - `WithPreRelease(true)` no longer suppresses the operator-level pre-release guards. It used to set a flag on the `Version` being tested that made diff --git a/version/padding_conformance_test.go b/version/padding_conformance_test.go new file mode 100644 index 0000000..82cc0db --- /dev/null +++ b/version/padding_conformance_test.go @@ -0,0 +1,198 @@ +// SPDX-License-Identifier: Apache-2.0 OR MIT + +// Regression tests for the release-blocking padding and epoch defects in +// prefix matching (`==X.*`, `!=X.*`) and the compatible operator (`~=`). +// +// Both shipped in v0.4.0 and both were inherited verbatim from the retired +// rstudio/go-pep440-version: +// +// F1 padVersion's zero-padding loops used `for i := 0; i < len(a)-len(b); i++` +// and APPENDED TO b INSIDE THE LOOP, so the bound shrank as the slice grew. +// They appended ceil(d/2) zeros for a gap of d, not d. +// F2 versionSplit did not prepend the epoch the way upstream's _version_split +// does, so "1!1.0" split to ["1!1", "0"]; the digit filter then dropped the +// "1!1" entirely and the under-padding made the two sides coincidentally +// equal, so `==0.0.0.*` MATCHED `1!1.0`. +// +// ⚠️ WHY THIS WENT UNNOTICED, and what this table is shaped to catch. +// +// ceil(1/2) == 1, so a gap of ONE segment is padded correctly by accident. Every +// pre-existing regression case in this area was a 1-segment gap, which is +// exactly why a real arithmetic bug survived a rewrite, a release, and a +// changelog entry claiming the padding worked "as PEP 440 requires". The table +// below sweeps gaps of 1 through 4 in BOTH directions, with zero and non-zero +// tails, pre-release segments, and epochs. +// +// ⚠️ The customer-visible case is `!=7.0.0.*` matching `7`: a repository server +// would SERVE a version pip EXCLUDES. It reaches PPM through arbitrary client +// input on POST /__api__/repos/:id/filter/packages. +// +// Every expected value is measured against pypa/packaging 26.2, not reasoned +// out. Measured before the fix: 30 of the 82 rows diverged, on v0.4.0 and on +// this branch identically. + +package version + +import ( + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestConformance_PaddingAndEpoch(t *testing.T) { + for _, tt := range paddingOracle { + t.Run(tt.spec+"__"+tt.version, func(t *testing.T) { + ss, err := NewSpecifiers(tt.spec, WithPreReleases(PreReleasesInclude)) + require.NoError(t, err, "specifier %q must parse", tt.spec) + v, err := Parse(tt.version) + require.NoError(t, err, "version %q must parse", tt.version) + assert.Equal(t, tt.want, ss.Check(v)) + + // The singular specifier must agree with the set. + s, err := NewSpecifier(tt.spec, WithPreReleases(PreReleasesInclude)) + require.NoError(t, err) + assert.Equal(t, tt.want, s.ContainsVersion(v), "singular must agree with the set") + }) + } +} + +// The arithmetic itself, independent of any specifier, so a future refactor of +// leftPad is checked directly rather than only through its callers. +// +// ⚠️ A gap of 1 is the case the old shrinking loop got RIGHT, so it cannot be +// the only case tested. +// The arithmetic itself, independent of any specifier, so a future refactor of +// leftPad is checked directly rather than only through its callers. +// +// ⚠️ A gap of 1 is the case the old shrinking loop got RIGHT, so it cannot be +// the only case tested. +func TestLeftPadFillsTheWholeGap(t *testing.T) { + for gap := 0; gap <= 5; gap++ { + split := []string{"0", "2"} + target := numericPrefixLen(split) + gap + got := leftPad(split, target) + assert.Equal(t, target, numericPrefixLen(got), + "gap %d: leftPad must reach the target numeric width", gap) + assert.Len(t, got, len(split)+gap, "gap %d: exactly gap zeros appended", gap) + } + + // With a suffix present the zeros go before it and the suffix survives. + for gap := 1; gap <= 4; gap++ { + split := []string{"0", "2", "rc1"} + got := leftPad(split, numericPrefixLen(split)+gap) + assert.Equal(t, "rc1", got[len(got)-1], "gap %d: suffix must stay last", gap) + assert.Len(t, got, len(split)+gap, "gap %d", gap) + } +} + +// The epoch must be its own leading component, which is what stops "1!1" from +// being mistaken for a non-numeric token and dropped. +// The epoch must be its own leading component, which is what stops "1!1" from +// being mistaken for a non-numeric token and dropped. +func TestVersionSplitPrependsTheEpoch(t *testing.T) { + tests := []struct { + in string + want []string + }{ + {"1.0", []string{"0", "1", "0"}}, + {"0!1.0", []string{"0", "1", "0"}}, + {"1!1.0", []string{"1", "1", "0"}}, + {"2!1", []string{"2", "1"}}, + } + for _, tt := range tests { + t.Run(tt.in, func(t *testing.T) { + assert.Equal(t, tt.want, versionSplit(tt.in)) + }) + } +} + +// 82 rows. Expected values measured against pypa/packaging 26.2. +var paddingOracle = []struct { + spec string + version string + want bool +}{ + {"==2.0.*", "2", true}, + {"==2.0.0.*", "2", true}, + {"!=7.0.0.*", "7", false}, + {"~=2.0.0.0", "2", true}, + {"==2.0.0.0.*", "2", true}, + {"==2.*", "2", true}, + {"!=2.*", "2", false}, + {"==2.*", "2.0", true}, + {"!=2.*", "2.0", false}, + {"==2.*", "2.0.0", true}, + {"!=2.*", "2.0.0", false}, + {"==2.*", "2.0.0.0", true}, + {"!=2.*", "2.0.0.0", false}, + {"==2.*", "2.0.0.0.0", true}, + {"!=2.*", "2.0.0.0.0", false}, + {"!=2.0.*", "2", false}, + {"==2.0.*", "2.0", true}, + {"!=2.0.*", "2.0", false}, + {"==2.0.*", "2.0.0", true}, + {"!=2.0.*", "2.0.0", false}, + {"==2.0.*", "2.0.0.0", true}, + {"!=2.0.*", "2.0.0.0", false}, + {"==2.0.*", "2.0.0.0.0", true}, + {"!=2.0.*", "2.0.0.0.0", false}, + {"!=2.0.0.*", "2", false}, + {"==2.0.0.*", "2.0", true}, + {"!=2.0.0.*", "2.0", false}, + {"==2.0.0.*", "2.0.0", true}, + {"!=2.0.0.*", "2.0.0", false}, + {"==2.0.0.*", "2.0.0.0", true}, + {"!=2.0.0.*", "2.0.0.0", false}, + {"==2.0.0.*", "2.0.0.0.0", true}, + {"!=2.0.0.*", "2.0.0.0.0", false}, + {"!=2.0.0.0.*", "2", false}, + {"==2.0.0.0.*", "2.0", true}, + {"!=2.0.0.0.*", "2.0", false}, + {"==2.0.0.0.*", "2.0.0", true}, + {"!=2.0.0.0.*", "2.0.0", false}, + {"==2.0.0.0.*", "2.0.0.0", true}, + {"!=2.0.0.0.*", "2.0.0.0", false}, + {"==2.0.0.0.*", "2.0.0.0.0", true}, + {"!=2.0.0.0.*", "2.0.0.0.0", false}, + {"==2.0.0.0.0.*", "2", true}, + {"!=2.0.0.0.0.*", "2", false}, + {"==2.0.0.0.0.*", "2.0", true}, + {"!=2.0.0.0.0.*", "2.0", false}, + {"==2.0.0.0.0.*", "2.0.0", true}, + {"!=2.0.0.0.0.*", "2.0.0", false}, + {"==2.0.0.0.0.*", "2.0.0.0", true}, + {"!=2.0.0.0.0.*", "2.0.0.0", false}, + {"==2.0.0.0.0.*", "2.0.0.0.0", true}, + {"!=2.0.0.0.0.*", "2.0.0.0.0", false}, + {"==1.2.0.0.*", "1.2", true}, + {"==1.2.*", "1.2.0.0", true}, + {"==1.0.0.0.0.*", "1", true}, + {"!=1.2.0.0.*", "1.2", false}, + {"==1.2.3.0.0.*", "1.2.3", true}, + {"==1.2.0.0.*", "1.2.0.0.0", true}, + {"==1.*", "1.0.0.0.0", true}, + {"==2.0.0.*", "2rc1", true}, + {"==2.0.0.*", "2.0rc1", true}, + {"==2.0.0.0.*", "2a1", true}, + {"!=2.0.0.*", "2rc1", false}, + {"==1.0.0.*", "1.0.0a1", true}, + {"==0.0.0.*", "1!1.0", false}, + {"~=0.0.0a1", "1!1.0", false}, + {"~=0.0.0rc1", "1!1.0", false}, + {"==0.0.*", "1!1.0", false}, + {"==1!1.0.*", "1!1.0", true}, + {"==1!1.*", "1!1.0", true}, + {"==1!1.0.0.*", "1!1", true}, + {"==2!1.0.0.0.*", "2!1", true}, + {"==1.0.*", "1!1.0", false}, + {"!=0.0.0.*", "1!1.0", true}, + {"==0!2.0.0.*", "2", true}, + {"~=1!1.0.0", "1!1.0.5", true}, + {"~=2.0", "2", true}, + {"~=2.0.0", "2", true}, + {"~=2.0.0.0.0", "2", true}, + {"~=1.2.0.0", "1.2", true}, + {"~=1.2", "1.2.0.0", true}, + {"~=1.2.0.0", "1.2.9.9", false}, +} diff --git a/version/specifier.go b/version/specifier.go index 9817e5b..785a8b8 100644 --- a/version/specifier.go +++ b/version/specifier.go @@ -5,9 +5,8 @@ package version import ( "errors" "fmt" - "reflect" "regexp" - "strconv" + "slices" "strings" ) @@ -622,52 +621,103 @@ func andCheck(v Version, specifiers []Specifier) bool { return true } +// versionSplit splits a version string into the components prefix matching and +// the compatible operator compare, ported from pypa/packaging 26.2's +// _version_split. +// +// Two details are load-bearing and were both missing from the earlier +// hand-rolled version: +// +// - The EPOCH is split off on "!" and becomes the first component, defaulting +// to "0". Without it, `2` and `0!2` split to different lengths and +// `==0!2.*` failed to match `2` even though they are the same version. +// - A release-plus-pre-release run in one dot-segment ("2rc1") is split into +// two components ("2", "rc1"), so that a pre-release behaves as its own +// segment for prefix purposes. +// +// The result is for comparison only; joining it back with versionJoin does not +// necessarily reproduce the input. func versionSplit(version string) []string { var result []string - for _, v := range strings.Split(version, ".") { - m := prefixRegexp.FindStringSubmatch(v) - if m != nil { + + // rpartition on "!": everything before the LAST "!" is the epoch. + epoch := "0" + rest := version + if i := strings.LastIndex(version, "!"); i >= 0 { + if version[:i] != "" { + epoch = version[:i] + } + rest = version[i+1:] + } + result = append(result, epoch) + + for _, item := range strings.Split(rest, ".") { + if m := prefixRegexp.FindStringSubmatch(item); m != nil { result = append(result, m[1:]...) } else { - result = append(result, v) + result = append(result, item) } } return result } -func isDigist(s string) bool { - if _, err := strconv.Atoi(s); err == nil { - return true +// versionJoin rebuilds a version string from a versionSplit result, ported from +// pypa/packaging 26.2's _version_join. The first component is the epoch. +func versionJoin(components []string) string { + if len(components) == 0 { + return "" } - return false + return components[0] + "!" + strings.Join(components[1:], ".") } -func padVersion(left, right []string) ([]string, []string) { - var leftRelease, rightRelease []string - for _, l := range left { - if isDigist(l) { - leftRelease = append(leftRelease, l) +// isNotSuffix reports whether a versionSplit component is part of the release +// segment rather than a pre/post/dev suffix. Ported from pypa/packaging 26.2's +// _is_not_suffix; it is the predicate the compatible operator uses to find +// where the release segment ends. +func isNotSuffix(segment string) bool { + for _, prefix := range []string{"dev", "a", "b", "rc", "post"} { + if strings.HasPrefix(segment, prefix) { + return false } } + return true +} - for _, r := range right { - if isDigist(r) { - rightRelease = append(rightRelease, r) +// numericPrefixLen counts the leading all-digit components of a versionSplit +// result. Ported from pypa/packaging 26.2's _numeric_prefix_len. +func numericPrefixLen(split []string) int { + count := 0 + for _, segment := range split { + if !isASCIIDigits(segment) { + break } + count++ } + return count +} - // Get the rest of our versions - leftRest := left[len(leftRelease):] - rightRest := right[len(rightRelease):] - - for i := 0; i < len(leftRelease)-len(rightRelease); i++ { - rightRelease = append(rightRelease, "0") - } - for i := 0; i < len(rightRelease)-len(leftRelease); i++ { - leftRelease = append(leftRelease, "0") - } - - return append(leftRelease, leftRest...), append(rightRelease, rightRest...) +// leftPad pads a versionSplit result with "0" components until it has +// targetNumericLen numeric components, preserving any suffix components. +// Ported from pypa/packaging 26.2's _left_pad. +// +// ⚠️ The padding is inserted AFTER the numeric prefix and BEFORE the suffix, +// which is what the earlier padVersion got wrong: it padded only to the other +// side's length and reassembled the two halves symmetrically, so `2` compared +// against the spec `2.0.0.*` was never widened to three numeric components and +// the prefix match failed. +func leftPad(split []string, targetNumericLen int) []string { + numericLen := numericPrefixLen(split) + padNeeded := targetNumericLen - numericLen + if padNeeded <= 0 { + return split + } + out := make([]string, 0, len(split)+padNeeded) + out = append(out, split[:numericLen]...) + for i := 0; i < padNeeded; i++ { + out = append(out, "0") + } + out = append(out, split[numericLen:]...) + return out } //------------------------------------------------------------------- @@ -704,66 +754,86 @@ func specifierCompatible(prospective Version, spec string) bool { // This allows us to implement this in terms of the other specifiers instead of implementing it ourselves. // The only thing we need to do is construct the other specifiers. + // Everything but the last item of the RELEASE segment. The loop stops at the + // first suffix component, so a pre-release in the operand is not mistaken + // for part of the release. + // + // ⚠️ The earlier version broke only on "post" and "dev", so a pre-release + // operand kept its "a1"/"rc1" component and then had it dropped as "the + // last item" -- which made `~=1.0a1` derive the prefix `1.*` rather than + // dropping only the release's last component. versionSplit now also + // prepends the epoch, so the operand and the prospective version agree on + // component count. var prefixElements []string for _, s := range versionSplit(spec) { - if strings.HasPrefix(s, "post") || strings.HasPrefix(s, "dev") { + if !isNotSuffix(s) { break } prefixElements = append(prefixElements, s) } - - // ⚠️ An operand whose FIRST dot-segment already starts with "post" or "dev" - // breaks the loop on iteration one, leaving prefixElements empty -- and - // slicing [:len-1] of an empty slice panics with "slice bounds out of range - // [:-1]". Reachable with the operand "dev1", "post1", "dev" or "post". + // ⚠️ This guard is load-bearing, not defensive decoration. + // + // Before versionSplit prepended the epoch, an operand whose FIRST segment + // was already a suffix ("dev1", "post1", "dev", "post") broke the loop on + // iteration one and left prefixElements empty -- and slicing [:len-1] of an + // empty slice panics with "slice bounds out of range [:-1]". With the epoch + // prepended there is always at least one element, so the panic is no longer + // reachable even from inside the package; the guard stays because that is a + // property of versionSplit rather than of this function. // - // This is the same landmine class as the MustParse sites, and note which - // operands DO NOT trigger it: "lolwat", "", "not a version" and "1.2.3.4.5-garbage" - // all pass through harmlessly, because they produce a non-empty first - // segment. A hardening test stocked only with those shapes therefore proves - // nothing about this line, which is exactly how it was missed. + // Note which operands do NOT trigger it: "lolwat", "", "not a version" and + // "1.2.3.4.5-garbage" all produce a non-empty first segment and pass through + // harmlessly. A hardening test stocked only with those shapes proves nothing + // about this line, which is exactly how it went unnoticed. The suffix-only + // shapes are covered in operand_hardening_test.go. if len(prefixElements) == 0 { return false } - // We want everything but the last item in the version, but we want to ignore post and dev releases, and - // we want to treat the pre-release as its own separate segment. - prefix := strings.Join(prefixElements[:len(prefixElements)-1], ".") - - // Add the prefix notation to the end of our string - prefix += ".*" + prefix := versionJoin(prefixElements[:len(prefixElements)-1]) + ".*" return specifierGreaterThanEqual(prospective, spec) && specifierEqual(prospective, prefix) } func specifierEqual(prospective Version, spec string) bool { - // https://github.com/pypa/packaging/blob/a6407e3a7e19bd979e93f58cfc7f6641a7378c46/packaging/specifiers.py#L476 - // We need special logic to handle prefix matching + // We need special logic to handle prefix matching. Ported from + // pypa/packaging 26.2's Specifier._compare_equal. if strings.HasSuffix(spec, ".*") { - // In the case of prefix matching we want to ignore local segment. + // In the case of prefix matching we want to ignore the local segment. public, ok := parseOperand(prospective.Public()) if !ok { return false } prospective = public - // Split the spec out by dots, and pretend that there is an implicit - // dot in between a release segment and a pre-release segment. - splitSpec := versionSplit(strings.TrimSuffix(spec, ".*")) + // Split the spec out by bangs and dots, pretending there is an implicit + // dot between a release segment and a pre-release segment. The operand + // goes through Parse first so that its normalized form (leading zeros, + // separator spellings, letter case) is what gets split -- otherwise + // `==1.01.*` and `==1.1.*` would split differently. + operand := strings.TrimSuffix(spec, ".*") + specVersion, ok := parseOperand(operand) + if !ok { + return false + } + splitSpec := versionSplit(specVersion.String()) + specNumericLen := numericPrefixLen(splitSpec) - // Split the prospective version out by dots, and pretend that there is an implicit dot - // in between a release segment and a pre-release segment. splitProspective := versionSplit(prospective.String()) - // Shorten the prospective version to be the same length as the spec - // so that we can determine if the specifier is a prefix of the - // prospective version or not. - if len(splitProspective) > len(splitSpec) { - splitProspective = splitProspective[:len(splitSpec)] + // ⚠️ Pad BEFORE shortening. Padding the prospective version up to the + // spec's numeric width first is what lets `2` match `==2.0.0.*`: it + // becomes ["0","2","0","0"], which then truncates to the spec exactly. + // Truncating first would have thrown away the room the padding needs. + paddedProspective := leftPad(splitProspective, specNumericLen) + + // Shorten the prospective version to the spec's length, so that the + // question becomes whether the spec is a prefix of it. + if len(paddedProspective) > len(splitSpec) { + paddedProspective = paddedProspective[:len(splitSpec)] } - paddedSpec, paddedProspective := padVersion(splitSpec, splitProspective) - return reflect.DeepEqual(paddedSpec, paddedProspective) + return slices.Equal(paddedProspective, splitSpec) } specVersion, ok := parseOperand(spec) diff --git a/version/specifier_test.go b/version/specifier_test.go index f8ee1f4..2d8c820 100644 --- a/version/specifier_test.go +++ b/version/specifier_test.go @@ -423,22 +423,84 @@ func TestVersion_Check(t *testing.T) { } } -// TestPadVersion_RightRestDerivesFromRight is a regression test for a bug where -// padVersion sliced left twice instead of slicing right for the "rest" of the -// right-hand version, so the returned right-hand segments were built from -// leftover pieces of the left-hand version instead of the right-hand version. -func TestPadVersion_RightRestDerivesFromRight(t *testing.T) { - // left's release segment ("2","0") is longer than right's ("3"), and each - // side has a distinct, differently-shaped non-numeric "rest" suffix, so a - // padVersion that mixes up which side the rest comes from is easy to spot. - left := []string{"2", "0", "rc1"} - right := []string{"3", "x"} - - _, gotRight := padVersion(left, right) - - // The right-hand rest must come from right (["x"]), not left (["rc1"]). - want := []string{"3", "0", "x"} - assert.Equal(t, want, gotRight) +// TestLeftPad_InsertsPaddingBeforeTheSuffix replaces the old +// TestPadVersion_RightRestDerivesFromRight. +// +// padVersion is gone: it padded the two sides against EACH OTHER and +// reassembled numeric prefix plus "rest" for both, and the bug it guarded +// against was slicing the left-hand side twice so the right-hand "rest" came +// from the wrong version. leftPad pads ONE side up to a target numeric width, +// with a single slice of a single input, so that class of mix-up is structurally +// impossible. +// +// What still has to hold, and is the substance of the old test, is that the "0" +// padding goes AFTER the numeric prefix and BEFORE any suffix segment, and that +// the suffix survives intact. +func TestLeftPad_InsertsPaddingBeforeTheSuffix(t *testing.T) { + tests := []struct { + name string + split []string + target int + want []string + }{ + { + // Ported from pypa/packaging 26.2's _left_pad docstring. + name: "upstream docstring example", + split: []string{"0", "1", "a1"}, + target: 4, + want: []string{"0", "1", "0", "0", "a1"}, + }, + { + name: "suffix is preserved, not overwritten", + split: []string{"0", "2", "rc1"}, + target: 3, + want: []string{"0", "2", "0", "rc1"}, + }, + { + name: "already wide enough is returned unchanged", + split: []string{"0", "1", "2", "3"}, + target: 3, + want: []string{"0", "1", "2", "3"}, + }, + { + name: "no suffix", + split: []string{"0", "2"}, + target: 4, + want: []string{"0", "2", "0", "0"}, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + assert.Equal(t, tt.want, leftPad(tt.split, tt.target)) + }) + } +} + +// versionSplit must peel the epoch off as its own leading component, and must +// treat a release-plus-pre-release run in one dot-segment as two components. +// Both were missing before, and both are why `==0!2.*` did not match `2`. +func TestVersionSplit_EpochAndPreRelease(t *testing.T) { + tests := []struct { + in string + want []string + }{ + {"2", []string{"0", "2"}}, + {"0!2", []string{"0", "2"}}, + {"2!1.0", []string{"2", "1", "0"}}, + {"2rc1", []string{"0", "2", "rc1"}}, + // The pre-release run is split out of its own dot-segment, so "0a1" + // becomes two components. Verified against pypa/packaging 26.2's + // _version_split. + {"1.0a1", []string{"0", "1", "0", "a1"}}, + {"1.0.post1", []string{"0", "1", "0", "post1"}}, + {"2.0.0", []string{"0", "2", "0", "0"}}, + } + for _, tt := range tests { + t.Run(tt.in, func(t *testing.T) { + assert.Equal(t, tt.want, versionSplit(tt.in)) + }) + } } // TestNewRSpecifiers_UsesProvidedSanitizer is a regression test for a bug where From 0fc4eec4699af5cc95a340bd2b77b9ab8a1ff11d Mon Sep 17 00:00:00 2001 From: Jonathan Yoder Date: Mon, 10 Aug 2026 14:12:21 -0400 Subject: [PATCH 7/7] Pin the PEP 440 alias family: the ~=1.0c1 asymmetry is conformance MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Reported as a bug: isNotSuffix omits "c", so ~=1.0c1 derives a narrower prefix than ~=1.0rc1 and the two spellings of one constraint disagree. ⚠️ I did NOT fix it, because measuring says there is nothing to fix. packaging 26.2 gives the same asymmetry: SpecifierSet("~=1.0c1").contains("1.1") -> False SpecifierSet("~=1.0rc1").contains("1.1") -> True gpp's isNotSuffix is a byte-faithful port of upstream's _is_not_suffix, which also checks only ("dev","a","b","rc","post"). The asymmetry comes from a mismatch between two UPSTREAM tables: _prefix_regex includes "c" (so 0c1 splits into 0 + c1) while _is_not_suffix does not (so the resulting c1 counts as release, not suffix). "c" is the only alias in that gap -- alpha and beta are caught incidentally because the check is a PREFIX match and they begin with "a"/"b", while pre, preview, r and rev never match _prefix_regex and stay whole. Both proposed fixes were measured and both make conformance WORSE: - adding "c" to the suffix list moves ~=1.0c1 away from the reference; - normalizing the operand through the parser before deriving the prefix -- the structural fix, which specifierEqual legitimately uses -- turns 0 divergences into 6, additionally breaking ~=1.0.pre1, ~=1.0.preview1, ~=1.0.r1, ~=1.0.rev1 and ~=1.0.c1, because upstream derives the prefix from the RAW operand text and those forms do not match _prefix_regex un-normalized. I applied the structural fix experimentally and counted before reverting, rather than arguing from the code. So the deliverable is evidence and a guard rather than a behavior change: a 410-row sweep covering every PEP 440 pre/post alias (a, alpha, b, beta, c, rc, pre, preview, post, r, rev, dev) against every permitted separator ("", ".", "-", "_") for both ~= and wildcard equality, measured against packaging 26.2. 0 divergences on both heads. ⚠️ Upstream's own test suite does not exercise "c" under ~=, so the ported conformance tables stay GREEN under the broken variant -- verified. That is why this sweep is separate from them: it is the only thing holding this behavior, and without it the next person to read PEP 440 will "fix" isNotSuffix and silently break six alias forms. isNotSuffix now carries a "DO NOT ADD C" note with the measurements, and a companion test pins both alias tables so the coupling is visible rather than discovered. Refs rstudio/package-manager#19383 Co-Authored-By: Claude Opus 5 (1M context) --- CHANGELOG.md | 31 ++ version/alias_conformance_test.go | 529 ++++++++++++++++++++++++++++++ version/specifier.go | 33 ++ 3 files changed, 593 insertions(+) create mode 100644 version/alias_conformance_test.go diff --git a/CHANGELOG.md b/CHANGELOG.md index fd5898d..5a449d2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -117,6 +117,37 @@ mistaken for a safe patch upgrade. divergence: the OR-of-ANDs shape this type carries for the R path (`a || b`) has no upstream counterpart to sort within. +### Notes + +- **`~=1.0c1` and `~=1.0rc1` answer differently, and that is conformance, not a bug.** + PEP 440 calls `c` an alias for `rc`, so this looks wrong; `packaging` 26.2 does the same + thing, measured: + + ``` + SpecifierSet("~=1.0c1").contains("1.1") -> False + SpecifierSet("~=1.0rc1").contains("1.1") -> True + ``` + + The cause is a mismatch between two upstream tables: `_prefix_regex` includes `c` (so + `0c1` splits into `0` + `c1`) while `_is_not_suffix` does not (so the resulting `c1` + counts as release rather than suffix), making the derived prefix one component narrower. + `c` is the only alias in that gap — `alpha`/`beta` are caught incidentally because the + check is a prefix match, and `pre`/`preview`/`r`/`rev` never match `_prefix_regex`. + + ⚠️ **Two candidate fixes were measured and both make conformance worse.** Adding `"c"` + to the suffix list moves `~=1.0c1` away from the reference. Normalizing the operand + through the parser before deriving the prefix — the structural fix, which + `specifierEqual` legitimately uses — turns **0 divergences into 6**, additionally + breaking `~=1.0.pre1`, `~=1.0.preview1`, `~=1.0.r1`, `~=1.0.rev1` and `~=1.0.c1`, + because upstream derives the prefix from the **raw** operand text. + + A new **410-row sweep** covers every PEP 440 pre/post alias against every permitted + separator for `~=` and wildcard equality, measured against `packaging` 26.2: **0 + divergences**. ⚠️ Upstream's own test suite does not exercise `c` under `~=`, so the + ported conformance tables cannot catch a change here — verified, they stay green under + the broken variant. This sweep is the only thing holding it, and `isNotSuffix` now + carries a "do not add c" note explaining why. + ### Added - `Specifier`, the exported **singular** specifier, with `Operator()`, `Version()`, diff --git a/version/alias_conformance_test.go b/version/alias_conformance_test.go new file mode 100644 index 0000000..1c32441 --- /dev/null +++ b/version/alias_conformance_test.go @@ -0,0 +1,529 @@ +// SPDX-License-Identifier: Apache-2.0 OR MIT + +// The PEP 440 pre-release / post-release ALIAS and SEPARATOR family, swept +// against pypa/packaging 26.2 for both `~=` and wildcard equality. +// +// PEP 440 defines `alpha`->`a`, `beta`->`b`, `c`/`pre`/`preview`->`rc`, +// `r`/`rev`->`post`, and permits `.`, `-` or `_` before the letter. This table +// covers every alias against every separator, because a fix that handles one +// token and leaves its siblings behind is the recurring failure mode in this +// area. +// +// ⚠️ WHAT THIS TABLE PINS, AND WHY IT IS NOT A BUG REPORT. +// +// `~=1.0c1` and `~=1.0rc1` give DIFFERENT answers -- `1.1` satisfies the second +// and not the first -- even though PEP 440 calls `c` an alias for `rc`. That +// asymmetry is upstream's, and this package reproduces it deliberately: +// +// packaging 26.2: SpecifierSet("~=1.0c1").contains("1.1") -> False +// SpecifierSet("~=1.0rc1").contains("1.1") -> True +// +// The cause is a mismatch between two upstream tables. `_prefix_regex` is +// `([0-9]+)((?:a|b|c|rc)[0-9]+)` and DOES include `c`, so `0c1` is split into +// `0` + `c1`; but `_is_not_suffix` checks only `("dev","a","b","rc","post")` and +// does NOT include `c`, so the resulting `c1` is treated as part of the release +// segment rather than as a suffix, and the derived prefix is one component +// narrower. `c` is the only alias that falls in that gap: `alpha`, `beta`, `pre` +// and `preview` never match `_prefix_regex` in the first place, so they stay +// whole and are handled consistently. +// +// ⚠️ Normalizing the operand through the parser before deriving the prefix -- +// the obvious structural fix, and one this package applies in specifierEqual -- +// is WRONG here. Measured: it turns 0 divergences into 6, breaking `~=1.0c1` +// plus the dot-separated `~=1.0.pre1`, `~=1.0.preview1`, `~=1.0.r1`, +// `~=1.0.rev1` and `~=1.0.c1`, because upstream derives the prefix from the RAW +// operand text and those forms do not match `_prefix_regex` un-normalized. +// +// ⚠️ Upstream's own test suite does not cover `c` under `~=`, so the ported +// conformance tables cannot catch a change here -- verified, they stay green +// under the broken variant. Only this independent sweep does, which is why it +// exists separately from the ported tables. + +package version + +import ( + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestConformance_PreReleaseAliasesAndSeparators(t *testing.T) { + for _, tt := range aliasOracle { + t.Run(tt.spec+"__"+tt.version, func(t *testing.T) { + ss, err := NewSpecifiers(tt.spec, WithPreReleases(PreReleasesInclude)) + require.NoError(t, err, "specifier %q must parse", tt.spec) + v, err := Parse(tt.version) + require.NoError(t, err, "version %q must parse", tt.version) + assert.Equal(t, tt.want, ss.Check(v)) + }) + } +} + +// The alias tables that produce the asymmetry, pinned directly so a future +// editor sees the coupling rather than discovering it. +// +// isNotSuffix omits "c" ON PURPOSE, mirroring upstream's _is_not_suffix. +// prefixRegexp includes "c", mirroring upstream's _prefix_regex. Changing either +// one alone changes ~= behavior; the test above measures the consequence. +func TestAliasTablesMatchUpstream(t *testing.T) { + // isNotSuffix recognizes exactly upstream's five prefixes. + suffixes := []string{"dev", "a", "b", "rc", "post"} + for _, s := range suffixes { + assert.False(t, isNotSuffix(s+"1"), "%q1 must be recognized as a suffix", s) + } + // ⚠️ The check is a PREFIX match, not an equality test, which is why the + // alias family splits three ways rather than two. Verified against + // upstream's _is_not_suffix one token at a time: + // + // recognized as a suffix (prefix-matches one of the five): + // dev1, a1, b1, rc1, post1, alpha1 (via "a"), beta1 (via "b") + // NOT recognized: + // c1, pre1, preview1, r1, rev1 + // + // So "alpha1" and "beta1" are caught incidentally by the "a" and "b" + // entries, while "c1", "pre1", "preview1", "r1" and "rev1" are not caught + // at all. + for _, s := range []string{"alpha1", "beta1"} { + assert.False(t, isNotSuffix(s), + "%q must prefix-match a suffix entry, as it does upstream", s) + } + for _, s := range []string{"c1", "pre1", "preview1", "r1", "rev1"} { + assert.True(t, isNotSuffix(s), + "%q must NOT be recognized as a suffix; upstream's _is_not_suffix does not "+ + "recognize it either, and adding it changes ~= answers away from the reference", s) + } + + // prefixRegexp DOES include c, which is the other half of the coupling. + assert.NotNil(t, prefixRegexp.FindStringSubmatch("0c1"), + `prefixRegexp must split "0c1"; upstream's _prefix_regex includes c`) + assert.NotNil(t, prefixRegexp.FindStringSubmatch("0rc1")) + assert.Nil(t, prefixRegexp.FindStringSubmatch("0alpha1"), + `prefixRegexp must NOT split "0alpha1"; upstream's does not either`) +} + +// 410 rows. Expected values measured against pypa/packaging 26.2. +// +// ⚠️ Note the asymmetry these rows PIN rather than fix: `~=1.0c1` and +// `~=1.0rc1` give DIFFERENT answers, even though PEP 440 defines `c` as an +// alias for `rc`. That is upstream's behavior, not this package's choice -- +// upstream's _prefix_regex includes `c` while its _is_not_suffix does not, so +// `c1` is split off as its own component and then treated as part of the +// release rather than as a suffix. Conforming to the reference is the point +// of these tables, so the rows record it; see isNotSuffix. +var aliasOracle = []struct { + spec string + version string + want bool +}{ + {"~=1.0a1", "1.1", true}, + {"~=1.0a1", "1.0", true}, + {"~=1.0a1", "1.0.1", true}, + {"~=1.0a1", "1.0.5", true}, + {"~=1.0a1", "2.0", false}, + {"~=1.0a1", "1.0c1", true}, + {"~=1.0a1", "1.0rc1", true}, + {"~=1.0a1", "0.9", false}, + {"~=1.0alpha1", "1.1", true}, + {"~=1.0alpha1", "1.0", true}, + {"~=1.0alpha1", "1.0.1", true}, + {"~=1.0alpha1", "1.0.5", true}, + {"~=1.0alpha1", "2.0", false}, + {"~=1.0alpha1", "1.0c1", true}, + {"~=1.0alpha1", "1.0rc1", true}, + {"~=1.0alpha1", "0.9", false}, + {"~=1.0b1", "1.1", true}, + {"~=1.0b1", "1.0", true}, + {"~=1.0b1", "1.0.1", true}, + {"~=1.0b1", "1.0.5", true}, + {"~=1.0b1", "2.0", false}, + {"~=1.0b1", "1.0c1", true}, + {"~=1.0b1", "1.0rc1", true}, + {"~=1.0b1", "0.9", false}, + {"~=1.0beta1", "1.1", true}, + {"~=1.0beta1", "1.0", true}, + {"~=1.0beta1", "1.0.1", true}, + {"~=1.0beta1", "1.0.5", true}, + {"~=1.0beta1", "2.0", false}, + {"~=1.0beta1", "1.0c1", true}, + {"~=1.0beta1", "1.0rc1", true}, + {"~=1.0beta1", "0.9", false}, + {"~=1.0c1", "1.1", false}, + {"~=1.0c1", "1.0", true}, + {"~=1.0c1", "1.0.1", true}, + {"~=1.0c1", "1.0.5", true}, + {"~=1.0c1", "2.0", false}, + {"~=1.0c1", "1.0c1", true}, + {"~=1.0c1", "1.0rc1", true}, + {"~=1.0c1", "0.9", false}, + {"~=1.0rc1", "1.1", true}, + {"~=1.0rc1", "1.0", true}, + {"~=1.0rc1", "1.0.1", true}, + {"~=1.0rc1", "1.0.5", true}, + {"~=1.0rc1", "2.0", false}, + {"~=1.0rc1", "1.0c1", true}, + {"~=1.0rc1", "1.0rc1", true}, + {"~=1.0rc1", "0.9", false}, + {"~=1.0pre1", "1.1", true}, + {"~=1.0pre1", "1.0", true}, + {"~=1.0pre1", "1.0.1", true}, + {"~=1.0pre1", "1.0.5", true}, + {"~=1.0pre1", "2.0", false}, + {"~=1.0pre1", "1.0c1", true}, + {"~=1.0pre1", "1.0rc1", true}, + {"~=1.0pre1", "0.9", false}, + {"~=1.0preview1", "1.1", true}, + {"~=1.0preview1", "1.0", true}, + {"~=1.0preview1", "1.0.1", true}, + {"~=1.0preview1", "1.0.5", true}, + {"~=1.0preview1", "2.0", false}, + {"~=1.0preview1", "1.0c1", true}, + {"~=1.0preview1", "1.0rc1", true}, + {"~=1.0preview1", "0.9", false}, + {"~=1.0.a1", "1.1", true}, + {"~=1.0.a1", "1.0", true}, + {"~=1.0.a1", "1.0.1", true}, + {"~=1.0.a1", "1.0.5", true}, + {"~=1.0.a1", "2.0", false}, + {"~=1.0.a1", "1.0c1", true}, + {"~=1.0.a1", "1.0rc1", true}, + {"~=1.0.a1", "0.9", false}, + {"~=1.0.alpha1", "1.1", true}, + {"~=1.0.alpha1", "1.0", true}, + {"~=1.0.alpha1", "1.0.1", true}, + {"~=1.0.alpha1", "1.0.5", true}, + {"~=1.0.alpha1", "2.0", false}, + {"~=1.0.alpha1", "1.0c1", true}, + {"~=1.0.alpha1", "1.0rc1", true}, + {"~=1.0.alpha1", "0.9", false}, + {"~=1.0.b1", "1.1", true}, + {"~=1.0.b1", "1.0", true}, + {"~=1.0.b1", "1.0.1", true}, + {"~=1.0.b1", "1.0.5", true}, + {"~=1.0.b1", "2.0", false}, + {"~=1.0.b1", "1.0c1", true}, + {"~=1.0.b1", "1.0rc1", true}, + {"~=1.0.b1", "0.9", false}, + {"~=1.0.beta1", "1.1", true}, + {"~=1.0.beta1", "1.0", true}, + {"~=1.0.beta1", "1.0.1", true}, + {"~=1.0.beta1", "1.0.5", true}, + {"~=1.0.beta1", "2.0", false}, + {"~=1.0.beta1", "1.0c1", true}, + {"~=1.0.beta1", "1.0rc1", true}, + {"~=1.0.beta1", "0.9", false}, + {"~=1.0.c1", "1.1", false}, + {"~=1.0.c1", "1.0", true}, + {"~=1.0.c1", "1.0.1", true}, + {"~=1.0.c1", "1.0.5", true}, + {"~=1.0.c1", "2.0", false}, + {"~=1.0.c1", "1.0c1", true}, + {"~=1.0.c1", "1.0rc1", true}, + {"~=1.0.c1", "0.9", false}, + {"~=1.0.rc1", "1.1", true}, + {"~=1.0.rc1", "1.0", true}, + {"~=1.0.rc1", "1.0.1", true}, + {"~=1.0.rc1", "1.0.5", true}, + {"~=1.0.rc1", "2.0", false}, + {"~=1.0.rc1", "1.0c1", true}, + {"~=1.0.rc1", "1.0rc1", true}, + {"~=1.0.rc1", "0.9", false}, + {"~=1.0.pre1", "1.1", false}, + {"~=1.0.pre1", "1.0", true}, + {"~=1.0.pre1", "1.0.1", true}, + {"~=1.0.pre1", "1.0.5", true}, + {"~=1.0.pre1", "2.0", false}, + {"~=1.0.pre1", "1.0c1", true}, + {"~=1.0.pre1", "1.0rc1", true}, + {"~=1.0.pre1", "0.9", false}, + {"~=1.0.preview1", "1.1", false}, + {"~=1.0.preview1", "1.0", true}, + {"~=1.0.preview1", "1.0.1", true}, + {"~=1.0.preview1", "1.0.5", true}, + {"~=1.0.preview1", "2.0", false}, + {"~=1.0.preview1", "1.0c1", true}, + {"~=1.0.preview1", "1.0rc1", true}, + {"~=1.0.preview1", "0.9", false}, + {"~=1.0-a1", "1.1", true}, + {"~=1.0-a1", "1.0", true}, + {"~=1.0-a1", "1.0.1", true}, + {"~=1.0-a1", "1.0.5", true}, + {"~=1.0-a1", "2.0", false}, + {"~=1.0-a1", "1.0c1", true}, + {"~=1.0-a1", "1.0rc1", true}, + {"~=1.0-a1", "0.9", false}, + {"~=1.0-alpha1", "1.1", true}, + {"~=1.0-alpha1", "1.0", true}, + {"~=1.0-alpha1", "1.0.1", true}, + {"~=1.0-alpha1", "1.0.5", true}, + {"~=1.0-alpha1", "2.0", false}, + {"~=1.0-alpha1", "1.0c1", true}, + {"~=1.0-alpha1", "1.0rc1", true}, + {"~=1.0-alpha1", "0.9", false}, + {"~=1.0-b1", "1.1", true}, + {"~=1.0-b1", "1.0", true}, + {"~=1.0-b1", "1.0.1", true}, + {"~=1.0-b1", "1.0.5", true}, + {"~=1.0-b1", "2.0", false}, + {"~=1.0-b1", "1.0c1", true}, + {"~=1.0-b1", "1.0rc1", true}, + {"~=1.0-b1", "0.9", false}, + {"~=1.0-beta1", "1.1", true}, + {"~=1.0-beta1", "1.0", true}, + {"~=1.0-beta1", "1.0.1", true}, + {"~=1.0-beta1", "1.0.5", true}, + {"~=1.0-beta1", "2.0", false}, + {"~=1.0-beta1", "1.0c1", true}, + {"~=1.0-beta1", "1.0rc1", true}, + {"~=1.0-beta1", "0.9", false}, + {"~=1.0-c1", "1.1", true}, + {"~=1.0-c1", "1.0", true}, + {"~=1.0-c1", "1.0.1", true}, + {"~=1.0-c1", "1.0.5", true}, + {"~=1.0-c1", "2.0", false}, + {"~=1.0-c1", "1.0c1", true}, + {"~=1.0-c1", "1.0rc1", true}, + {"~=1.0-c1", "0.9", false}, + {"~=1.0-rc1", "1.1", true}, + {"~=1.0-rc1", "1.0", true}, + {"~=1.0-rc1", "1.0.1", true}, + {"~=1.0-rc1", "1.0.5", true}, + {"~=1.0-rc1", "2.0", false}, + {"~=1.0-rc1", "1.0c1", true}, + {"~=1.0-rc1", "1.0rc1", true}, + {"~=1.0-rc1", "0.9", false}, + {"~=1.0-pre1", "1.1", true}, + {"~=1.0-pre1", "1.0", true}, + {"~=1.0-pre1", "1.0.1", true}, + {"~=1.0-pre1", "1.0.5", true}, + {"~=1.0-pre1", "2.0", false}, + {"~=1.0-pre1", "1.0c1", true}, + {"~=1.0-pre1", "1.0rc1", true}, + {"~=1.0-pre1", "0.9", false}, + {"~=1.0-preview1", "1.1", true}, + {"~=1.0-preview1", "1.0", true}, + {"~=1.0-preview1", "1.0.1", true}, + {"~=1.0-preview1", "1.0.5", true}, + {"~=1.0-preview1", "2.0", false}, + {"~=1.0-preview1", "1.0c1", true}, + {"~=1.0-preview1", "1.0rc1", true}, + {"~=1.0-preview1", "0.9", false}, + {"~=1.0_a1", "1.1", true}, + {"~=1.0_a1", "1.0", true}, + {"~=1.0_a1", "1.0.1", true}, + {"~=1.0_a1", "1.0.5", true}, + {"~=1.0_a1", "2.0", false}, + {"~=1.0_a1", "1.0c1", true}, + {"~=1.0_a1", "1.0rc1", true}, + {"~=1.0_a1", "0.9", false}, + {"~=1.0_alpha1", "1.1", true}, + {"~=1.0_alpha1", "1.0", true}, + {"~=1.0_alpha1", "1.0.1", true}, + {"~=1.0_alpha1", "1.0.5", true}, + {"~=1.0_alpha1", "2.0", false}, + {"~=1.0_alpha1", "1.0c1", true}, + {"~=1.0_alpha1", "1.0rc1", true}, + {"~=1.0_alpha1", "0.9", false}, + {"~=1.0_b1", "1.1", true}, + {"~=1.0_b1", "1.0", true}, + {"~=1.0_b1", "1.0.1", true}, + {"~=1.0_b1", "1.0.5", true}, + {"~=1.0_b1", "2.0", false}, + {"~=1.0_b1", "1.0c1", true}, + {"~=1.0_b1", "1.0rc1", true}, + {"~=1.0_b1", "0.9", false}, + {"~=1.0_beta1", "1.1", true}, + {"~=1.0_beta1", "1.0", true}, + {"~=1.0_beta1", "1.0.1", true}, + {"~=1.0_beta1", "1.0.5", true}, + {"~=1.0_beta1", "2.0", false}, + {"~=1.0_beta1", "1.0c1", true}, + {"~=1.0_beta1", "1.0rc1", true}, + {"~=1.0_beta1", "0.9", false}, + {"~=1.0_c1", "1.1", true}, + {"~=1.0_c1", "1.0", true}, + {"~=1.0_c1", "1.0.1", true}, + {"~=1.0_c1", "1.0.5", true}, + {"~=1.0_c1", "2.0", false}, + {"~=1.0_c1", "1.0c1", true}, + {"~=1.0_c1", "1.0rc1", true}, + {"~=1.0_c1", "0.9", false}, + {"~=1.0_rc1", "1.1", true}, + {"~=1.0_rc1", "1.0", true}, + {"~=1.0_rc1", "1.0.1", true}, + {"~=1.0_rc1", "1.0.5", true}, + {"~=1.0_rc1", "2.0", false}, + {"~=1.0_rc1", "1.0c1", true}, + {"~=1.0_rc1", "1.0rc1", true}, + {"~=1.0_rc1", "0.9", false}, + {"~=1.0_pre1", "1.1", true}, + {"~=1.0_pre1", "1.0", true}, + {"~=1.0_pre1", "1.0.1", true}, + {"~=1.0_pre1", "1.0.5", true}, + {"~=1.0_pre1", "2.0", false}, + {"~=1.0_pre1", "1.0c1", true}, + {"~=1.0_pre1", "1.0rc1", true}, + {"~=1.0_pre1", "0.9", false}, + {"~=1.0_preview1", "1.1", true}, + {"~=1.0_preview1", "1.0", true}, + {"~=1.0_preview1", "1.0.1", true}, + {"~=1.0_preview1", "1.0.5", true}, + {"~=1.0_preview1", "2.0", false}, + {"~=1.0_preview1", "1.0c1", true}, + {"~=1.0_preview1", "1.0rc1", true}, + {"~=1.0_preview1", "0.9", false}, + {"~=1.0post1", "1.1", true}, + {"~=1.0post1", "1.0", false}, + {"~=1.0post1", "1.0.1", true}, + {"~=1.0post1", "1.0.5", true}, + {"~=1.0post1", "2.0", false}, + {"~=1.0post1", "1.0c1", false}, + {"~=1.0post1", "1.0rc1", false}, + {"~=1.0post1", "0.9", false}, + {"~=1.0r1", "1.1", true}, + {"~=1.0r1", "1.0", false}, + {"~=1.0r1", "1.0.1", true}, + {"~=1.0r1", "1.0.5", true}, + {"~=1.0r1", "2.0", false}, + {"~=1.0r1", "1.0c1", false}, + {"~=1.0r1", "1.0rc1", false}, + {"~=1.0r1", "0.9", false}, + {"~=1.0rev1", "1.1", true}, + {"~=1.0rev1", "1.0", false}, + {"~=1.0rev1", "1.0.1", true}, + {"~=1.0rev1", "1.0.5", true}, + {"~=1.0rev1", "2.0", false}, + {"~=1.0rev1", "1.0c1", false}, + {"~=1.0rev1", "1.0rc1", false}, + {"~=1.0rev1", "0.9", false}, + {"~=1.0.post1", "1.1", true}, + {"~=1.0.post1", "1.0", false}, + {"~=1.0.post1", "1.0.1", true}, + {"~=1.0.post1", "1.0.5", true}, + {"~=1.0.post1", "2.0", false}, + {"~=1.0.post1", "1.0c1", false}, + {"~=1.0.post1", "1.0rc1", false}, + {"~=1.0.post1", "0.9", false}, + {"~=1.0.r1", "1.1", false}, + {"~=1.0.r1", "1.0", false}, + {"~=1.0.r1", "1.0.1", true}, + {"~=1.0.r1", "1.0.5", true}, + {"~=1.0.r1", "2.0", false}, + {"~=1.0.r1", "1.0c1", false}, + {"~=1.0.r1", "1.0rc1", false}, + {"~=1.0.r1", "0.9", false}, + {"~=1.0.rev1", "1.1", false}, + {"~=1.0.rev1", "1.0", false}, + {"~=1.0.rev1", "1.0.1", true}, + {"~=1.0.rev1", "1.0.5", true}, + {"~=1.0.rev1", "2.0", false}, + {"~=1.0.rev1", "1.0c1", false}, + {"~=1.0.rev1", "1.0rc1", false}, + {"~=1.0.rev1", "0.9", false}, + {"~=1.0-post1", "1.1", true}, + {"~=1.0-post1", "1.0", false}, + {"~=1.0-post1", "1.0.1", true}, + {"~=1.0-post1", "1.0.5", true}, + {"~=1.0-post1", "2.0", false}, + {"~=1.0-post1", "1.0c1", false}, + {"~=1.0-post1", "1.0rc1", false}, + {"~=1.0-post1", "0.9", false}, + {"~=1.0-r1", "1.1", true}, + {"~=1.0-r1", "1.0", false}, + {"~=1.0-r1", "1.0.1", true}, + {"~=1.0-r1", "1.0.5", true}, + {"~=1.0-r1", "2.0", false}, + {"~=1.0-r1", "1.0c1", false}, + {"~=1.0-r1", "1.0rc1", false}, + {"~=1.0-r1", "0.9", false}, + {"~=1.0-rev1", "1.1", true}, + {"~=1.0-rev1", "1.0", false}, + {"~=1.0-rev1", "1.0.1", true}, + {"~=1.0-rev1", "1.0.5", true}, + {"~=1.0-rev1", "2.0", false}, + {"~=1.0-rev1", "1.0c1", false}, + {"~=1.0-rev1", "1.0rc1", false}, + {"~=1.0-rev1", "0.9", false}, + {"~=1.0_post1", "1.1", true}, + {"~=1.0_post1", "1.0", false}, + {"~=1.0_post1", "1.0.1", true}, + {"~=1.0_post1", "1.0.5", true}, + {"~=1.0_post1", "2.0", false}, + {"~=1.0_post1", "1.0c1", false}, + {"~=1.0_post1", "1.0rc1", false}, + {"~=1.0_post1", "0.9", false}, + {"~=1.0_r1", "1.1", true}, + {"~=1.0_r1", "1.0", false}, + {"~=1.0_r1", "1.0.1", true}, + {"~=1.0_r1", "1.0.5", true}, + {"~=1.0_r1", "2.0", false}, + {"~=1.0_r1", "1.0c1", false}, + {"~=1.0_r1", "1.0rc1", false}, + {"~=1.0_r1", "0.9", false}, + {"~=1.0_rev1", "1.1", true}, + {"~=1.0_rev1", "1.0", false}, + {"~=1.0_rev1", "1.0.1", true}, + {"~=1.0_rev1", "1.0.5", true}, + {"~=1.0_rev1", "2.0", false}, + {"~=1.0_rev1", "1.0c1", false}, + {"~=1.0_rev1", "1.0rc1", false}, + {"~=1.0_rev1", "0.9", false}, + {"~=1.0dev1", "1.1", true}, + {"~=1.0dev1", "1.0", true}, + {"~=1.0dev1", "1.0.1", true}, + {"~=1.0dev1", "1.0.5", true}, + {"~=1.0dev1", "2.0", false}, + {"~=1.0dev1", "1.0c1", true}, + {"~=1.0dev1", "1.0rc1", true}, + {"~=1.0dev1", "0.9", false}, + {"~=1.0.dev1", "1.1", true}, + {"~=1.0.dev1", "1.0", true}, + {"~=1.0.dev1", "1.0.1", true}, + {"~=1.0.dev1", "1.0.5", true}, + {"~=1.0.dev1", "2.0", false}, + {"~=1.0.dev1", "1.0c1", true}, + {"~=1.0.dev1", "1.0rc1", true}, + {"~=1.0.dev1", "0.9", false}, + {"~=1.0-dev1", "1.1", true}, + {"~=1.0-dev1", "1.0", true}, + {"~=1.0-dev1", "1.0.1", true}, + {"~=1.0-dev1", "1.0.5", true}, + {"~=1.0-dev1", "2.0", false}, + {"~=1.0-dev1", "1.0c1", true}, + {"~=1.0-dev1", "1.0rc1", true}, + {"~=1.0-dev1", "0.9", false}, + {"~=1.0_dev1", "1.1", true}, + {"~=1.0_dev1", "1.0", true}, + {"~=1.0_dev1", "1.0.1", true}, + {"~=1.0_dev1", "1.0.5", true}, + {"~=1.0_dev1", "2.0", false}, + {"~=1.0_dev1", "1.0c1", true}, + {"~=1.0_dev1", "1.0rc1", true}, + {"~=1.0_dev1", "0.9", false}, + {"==1.*", "1.0", true}, + {"==1.0.*", "1.0", true}, + {"==1.*", "1.1", true}, + {"==1.0.*", "1.1", false}, + {"==1.*", "1.0a1", true}, + {"==1.0.*", "1.0a1", true}, + {"==1.*", "1.0alpha1", true}, + {"==1.0.*", "1.0alpha1", true}, + {"==1.*", "1.0b1", true}, + {"==1.0.*", "1.0b1", true}, + {"==1.*", "1.0beta1", true}, + {"==1.0.*", "1.0beta1", true}, + {"==1.*", "1.0c1", true}, + {"==1.0.*", "1.0c1", true}, + {"==1.*", "1.0rc1", true}, + {"==1.0.*", "1.0rc1", true}, + {"==1.*", "1.0pre1", true}, + {"==1.0.*", "1.0pre1", true}, + {"==1.*", "1.0preview1", true}, + {"==1.0.*", "1.0preview1", true}, + {"==1.*", "1.0post1", true}, + {"==1.0.*", "1.0post1", true}, + {"==1.*", "1.0r1", true}, + {"==1.0.*", "1.0r1", true}, + {"==1.*", "1.0rev1", true}, + {"==1.0.*", "1.0rev1", true}, +} diff --git a/version/specifier.go b/version/specifier.go index 785a8b8..de51f7a 100644 --- a/version/specifier.go +++ b/version/specifier.go @@ -674,6 +674,39 @@ func versionJoin(components []string) string { // segment rather than a pre/post/dev suffix. Ported from pypa/packaging 26.2's // _is_not_suffix; it is the predicate the compatible operator uses to find // where the release segment ends. +// +// ⚠️ THE LIST OMITS "c" ON PURPOSE. DO NOT ADD IT. +// +// PEP 440 defines `c` as an alias for `rc`, so omitting it looks like an +// oversight, and its consequence looks like a bug: `~=1.0c1` derives a narrower +// prefix than `~=1.0rc1`, so `1.1` satisfies the second and not the first. But +// that is exactly what the reference implementation does, measured: +// +// packaging 26.2: SpecifierSet("~=1.0c1").contains("1.1") -> False +// SpecifierSet("~=1.0rc1").contains("1.1") -> True +// +// The asymmetry comes from a mismatch between two upstream tables, not from +// this port: `_prefix_regex` DOES include `c` (so `0c1` is split into `0` + `c1`) +// while `_is_not_suffix` does NOT (so the resulting `c1` counts as release +// rather than suffix). `c` is the only alias in that gap -- `alpha` and `beta` +// are caught incidentally because this is a PREFIX match and they begin with +// "a" and "b", while `pre`, `preview`, `r` and `rev` never match +// `_prefix_regex` and so stay whole. +// +// Two fixes were measured and both make conformance WORSE: +// +// - adding "c" here changes `~=1.0c1` away from the reference; +// - normalizing the operand through the parser before deriving the prefix +// (the structural fix, which specifierEqual legitimately uses) turns 0 +// divergences into 6, additionally breaking `~=1.0.pre1`, `~=1.0.preview1`, +// `~=1.0.r1`, `~=1.0.rev1` and `~=1.0.c1`, because upstream derives the +// prefix from the RAW operand text and those forms do not match +// `_prefix_regex` un-normalized. +// +// ⚠️ Upstream's own test suite does not exercise `c` under `~=`, so the ported +// conformance tables stay green either way. The 410-row sweep in +// alias_conformance_test.go is what holds this, and it is the only thing that +// does. func isNotSuffix(segment string) bool { for _, prefix := range []string{"dev", "a", "b", "rc", "post"} { if strings.HasPrefix(segment, prefix) {