From 6337ece9af47a012563791cddeca7f77e425e031 Mon Sep 17 00:00:00 2001 From: Jonathan Yoder Date: Thu, 6 Aug 2026 07:50:03 -0400 Subject: [PATCH] fix(pep508): require a comma between version specifiers, and stop inventing one MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit PEP 508 requires a comma between version specifiers. We accepted them written adjacently -- and did not merely accept them. We RE-RENDERED WITH A COMMA THE INPUT NEVER CONTAINED: "urllib3 (>=1.26<2.0)" came back as "urllib3>=1.26,<2.0". Fabricating a constraint boundary out of malformed input is a wrong answer delivered confidently; the publisher's intent is unknowable from that string, and guessing it silently changes which versions resolve. MEASURED over 2,804,135 distinct requirement strings from a production PyPI snapshot (76,741,586 total entries): 756 were accepted with an invented comma. After this change 20 remain, all reaching the same symptom by a different route (see below), and rejections rise by exactly the difference. ROOT CAUSE was the tokenizer's version pattern, not the grammar. The parser loop already required a Comma between clauses, so the leniency was invisible there: the Specifier token's operand was `[^\s,;)]+`, "anything that is not a delimiter", which swallowed "1.5.0>=1.2.0" whole as a single "version". version.NewSpecifiers then re-split that on operators and rendered the comma. The fix follows upstream's structure, which splits the pattern by operator rather than using one permissive operand: "===" is arbitrary equality, whose operand PEP 440 defines as an opaque string that is never interpreted as a version, so it keeps the permissive run; every other operator excludes "<>=~" so two specifiers cannot fuse. ⚠️ "!" DELIBERATELY STAYS ADMISSIBLE, because a PEP 440 epoch contains one ("1!2.0"). Excluding it alongside the other operator characters is the obvious next step and it breaks every epoch specifier -- verified by mutation, which is why there is a test for it. ⚠️ TWO FURTHER DIVERGENCES WERE FOUND AND ARE DELIBERATELY NOT FIXED HERE. Both predate this change -- each confirmed to behave identically on unmodified main -- and both are documented beside the tests: 1. An uppercase or underscored local label in a SPECIFIER is rejected: "foo ==1.0+UBUNTU_1" errors while upstream accepts it and renders it verbatim. 2. validConstraintRegexp makes the comma between constraints OPTIONAL, and its operator alternation admits an empty operator so a bare version is a valid constraint. Together those let constraints run together: "==0.1dev10.3" parses as "==0.1dev10" plus a bare-version constraint "3" and renders "==0.1dev10,3". That is the same fabricated-comma failure by another route, and it accounts for the 20 remaining cases. The second is the one to be careful with, and the reason it is not in this PR: that regex is shared with NewRSpecifiers, which Package Manager uses for R constraint parsing. Requiring a comma there needs measuring against R data rather than being assumed safe from the Python side. ⚠️ ANOTHER OF MY TEST EXPECTATIONS WAS WRONG, found by measuring rather than reading. I asserted "foo ==1.0+ubuntu-1" would render its local label normalized to "ubuntu.1". It does not, and should not: upstream normalizes a bare Version but renders a SPECIFIER's operand verbatim -- SpecifierSet("==1.0+ubuntu-1") is unchanged while Version("1.0+ubuntu-1") becomes "1.0+ubuntu.1". Our behaviour already matched; my expectation did not. Verified by mutation: restoring the old permissive rule fails the adjacency test while leaving the others passing; narrowing "===" too fails the arbitrary-equality test; excluding "!" fails the epoch case. The full suite, including the pypa-ported conformance tables and the rapid property tests, is unchanged and green. CHANGELOG entry goes in 0.2.0's Breaking section rather than Unreleased, since that tag is not cut yet and 0.2.0 is billed as the conformance release. Move it if you would rather cut 0.2.0 as it stands. Refs rstudio/package-manager#19466 Co-Authored-By: Claude Opus 5 --- CHANGELOG.md | 7 ++ internal/pep508/tokenizer.go | 27 +++-- requirement/adjacent_specifier_test.go | 131 +++++++++++++++++++++++++ 3 files changed, 159 insertions(+), 6 deletions(-) create mode 100644 requirement/adjacent_specifier_test.go diff --git a/CHANGELOG.md b/CHANGELOG.md index 2f6e18b..a270142 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -21,6 +21,13 @@ rather than `0.1.3`. ### Breaking +- Two version specifiers written adjacently with no comma are rejected, as PEP 508 requires + and as upstream does. `foo (>=1.0<2.0)` and `foo>=1.0<2.0` previously parsed. + **They did not merely parse — they re-rendered with a comma the input never contained**, + turning `urllib3 (>=1.26<2.0)` into `urllib3>=1.26,<2.0` and so fabricating a constraint + boundary from malformed input. Measured over 2,804,135 distinct requirement strings in a + production PyPI snapshot, 756 were affected. Arbitrary equality (`===`) is unchanged and + still takes an opaque operand, which may contain operator characters. - `Specifiers.Check` returns `true` for a specifier set holding no specifiers, where it previously returned `false` for every version. PEP 508 makes a requirement's version specifier optional and an omitted one accepts any version, which upstream spells as an diff --git a/internal/pep508/tokenizer.go b/internal/pep508/tokenizer.go index 1203e86..6f02b99 100644 --- a/internal/pep508/tokenizer.go +++ b/internal/pep508/tokenizer.go @@ -207,12 +207,27 @@ var tokenRules = map[Kind]*regexp.Regexp{ Comma: regexp.MustCompile(`\A,`), Semicolon: regexp.MustCompile(`\A;`), AT: regexp.MustCompile(`\A@`), - // Specifier: an OP (reusing the same longest-first alternation as the - // OP rule) followed by optional whitespace and a version-shaped run - // of characters, bounded by whitespace/comma/semicolon/closing-paren - // rather than a precise PEP 440 grammar - version.NewSpecifiers is - // the authoritative parser for the accumulated raw text. - Specifier: regexp.MustCompile(`\A(?:===|==|~=|!=|<=|>=|<|>)\s*[^\s,;)]+`), + // Specifier: an OP followed by optional whitespace and a version, split + // by operator the way upstream packaging's specifier regex is. + // + // "===" is arbitrary equality: PEP 440 says its operand is an opaque + // string that is never interpreted as a version, so it takes anything up + // to a delimiter. + // + // ⚠️ EVERY OTHER OPERATOR MUST EXCLUDE THE OPERATOR CHARACTERS "<>=~", or + // two adjacent specifiers FUSE INTO ONE TOKEN. With a single permissive + // run of non-delimiters, "<1.5.0>=1.2.0" tokenized as one specifier whose + // "version" was "1.5.0>=1.2.0"; version.NewSpecifiers then re-split that + // on operators and rendered "<1.5.0,>=1.2.0", INVENTING A COMMA the input + // never contained. PEP 508 requires a comma between specifiers and + // upstream rejects all such inputs, so accepting them both diverged from + // the spec and fabricated a constraint boundary. + // + // "!" stays admissible because a PEP 440 epoch contains one ("1!2.0"). + // That means "<1.0!=2.0" tokenizes as "<1.0!" and then fails on the + // leftover "=2.0" rather than at the fusion point, which is a worse error + // message for the same correct verdict. + Specifier: regexp.MustCompile(`\A(?:===\s*[^\s,;)]+|(?:==|~=|!=|<=|>=|<|>)\s*[^\s,;)<>=~]+)`), // URL: a greedy run of non-whitespace characters - the exact // complement of the WS rule above (\s+) - deliberately not bounded by // ";" (see the URL Kind doc comment). Upstream packaging's rule diff --git a/requirement/adjacent_specifier_test.go b/requirement/adjacent_specifier_test.go new file mode 100644 index 0000000..c658664 --- /dev/null +++ b/requirement/adjacent_specifier_test.go @@ -0,0 +1,131 @@ +// SPDX-License-Identifier: Apache-2.0 OR MIT + +package requirement + +import ( + "strings" + "testing" +) + +// PEP 508 requires a comma between version specifiers. Two specifiers written +// adjacently, with no comma, is invalid input — and accepting it was worse than +// a conformance gap, because we did not merely admit it, we RENDERED A COMMA THE +// INPUT NEVER CONTAINED. +// +// Measured on a production PyPI snapshot of 2,804,135 distinct requirement +// strings: 756 were accepted and re-rendered with a fabricated comma, e.g. +// "urllib3 (>=1.26<2.0)" became "urllib3>=1.26,<2.0". Fabricating a constraint +// boundary is a wrong answer delivered confidently — the publisher's intent is +// unknowable from malformed input, and guessing it silently changes which +// versions resolve. +// +// Expected verdicts below are the MEASURED behaviour of pypa/packaging 26.2, +// which rejects every one of these. +func TestAdjacentSpecifiersRequireAComma(t *testing.T) { + for _, tc := range []struct { + in string + reason string + }{ + {"azure-identity (<1.5.0>=1.2.0)", "parenthesized, two specifiers, no comma"}, + {"azure-identity<1.5.0>=1.2.0", "unparenthesized, two specifiers, no comma"}, + {"foo (>=1.0<2.0)", "the shape seen most often in the real corpus"}, + {"urllib3 (>=1.26<2.0)", "a real example from the snapshot"}, + {"boto3 (>=1.23.10<1.24.0)", "a real example from the snapshot"}, + {"textual>=0.2.1<1", "a real example, unparenthesized"}, + {"locate (>=1.0==1.*)", "a real example mixing operators"}, + {"foo >=1.0 <2.0", "whitespace is not a separator either"}, + } { + if _, err := Parse(tc.in); err == nil { + t.Errorf("Parse(%q) was accepted; PEP 508 requires a comma between specifiers "+ + "and upstream rejects it (%s)", tc.in, tc.reason) + } + } +} + +// TestCommaSeparatedSpecifiersStillParse is the other direction, and it is not a +// formality: the fix narrows a character class in the tokenizer, so the risk is +// rejecting valid input rather than accepting invalid input. +func TestCommaSeparatedSpecifiersStillParse(t *testing.T) { + for _, tc := range []struct{ in, want string }{ + {"azure-identity (<1.5.0,>=1.2.0)", "azure-identity<1.5.0,>=1.2.0"}, + {"foo >=1.0,<2.0", "foo>=1.0,<2.0"}, + {"foo (>=1.0)", "foo>=1.0"}, + {"foo", "foo"}, + {"foo == 1.0", "foo==1.0"}, + {"foo ~= 1.4.5", "foo~=1.4.5"}, + {"foo != 1.0", "foo!=1.0"}, + {"foo == 1.0.*", "foo==1.0.*"}, + // An epoch contains "!", which the narrowed class must still admit. + {"foo ==1!2.0", "foo==1!2.0"}, + {"foo >=1!2.0,<1!3.0", "foo>=1!2.0,<1!3.0"}, + // A local version contains "+" and "-", both of which the narrowed class + // must still admit. + // + // ⚠️ Rendered VERBATIM, not normalized to "ubuntu.1". A bare Version does + // normalize its local label, but a specifier's operand does not — measured + // against pypa/packaging 26.2, where SpecifierSet("==1.0+ubuntu-1") renders + // unchanged while Version("1.0+ubuntu-1") becomes "1.0+ubuntu.1". My first + // draft of this case asserted the normalized form and was simply wrong + // about the reference. + {"foo ==1.0+ubuntu-1", "foo==1.0+ubuntu-1"}, + } { + r, err := Parse(tc.in) + if err != nil { + t.Errorf("Parse(%q): unexpected error %v", tc.in, err) + continue + } + if got := r.String(); got != tc.want { + t.Errorf("Parse(%q).String() = %q, want %q", tc.in, got, tc.want) + } + } +} + +// ⚠️ TWO SEPARATE DIVERGENCES FROM THE REFERENCE WERE FOUND WHILE WRITING THESE +// TESTS AND ARE DELIBERATELY NOT FIXED HERE. Both predate this change — each was +// confirmed to behave identically on unmodified main — and each needs a decision +// this change should not make on its own. +// +// 1. An uppercase or underscored local label in a SPECIFIER is rejected: +// "foo ==1.0+UBUNTU_1" errors with "improper constraint", while +// pypa/packaging accepts it and renders it verbatim. The version regex behind +// validConstraintRegexp is stricter than PEP 440's raw local-label grammar. +// +// 2. The comma between constraints is OPTIONAL in validConstraintRegexp +// (a trailing `\,?` inside a repeated group), and the operator alternation +// admits an empty operator so a bare version is a valid constraint. Together +// those let adjacent constraints run together: "==0.1dev10.3" parses as +// "==0.1dev10" followed by a bare-version constraint "3", and renders +// "==0.1dev10,3" — the same fabricated-comma failure as above, arriving by a +// different route. It accounts for the 20 cases that remain after this fix, +// down from 756. +// +// The second is the one to be careful with: that regex is shared with +// NewRSpecifiers, which Package Manager uses for R constraint parsing, so +// requiring a comma there needs to be measured against R data rather than +// assumed safe from the Python side. + +// TestArbitraryEqualityKeepsItsPermissiveOperand guards the one operator that +// must NOT be narrowed. +// +// PEP 440 defines "===" as an escape hatch comparing an opaque string that is +// never interpreted as a version, so its operand may legitimately contain the +// characters excluded for every other operator. Narrowing it along with the rest +// would have been an easy and invisible mistake — the corpus has few such +// requirements, so nothing else here would have caught it. +func TestArbitraryEqualityKeepsItsPermissiveOperand(t *testing.T) { + for _, in := range []string{ + "foo ===lolwat", + "foo ===1.0>=2.0", + "foo ===<>=~", + "foo (===anything-at-all)", + } { + r, err := Parse(in) + if err != nil { + t.Errorf("Parse(%q): arbitrary equality takes an opaque operand, got error %v", in, err) + continue + } + if !strings.Contains(r.String(), "===") { + t.Errorf("Parse(%q).String() = %q, expected it to retain ===", in, r.String()) + } + } +}