Repository navigation
Add the public specifier and marker API that PEP 440/508 conformance assertions need (rstudio/package-manager#19383) - #28
Conversation
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) <noreply@anthropic.com>
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) <noreply@anthropic.com>
RoboRev findings addressed —
|
| operation | verdict |
|---|---|
Check, String, Contains, Filter, matchAll, allArbitraryMatch |
already walked the groups — correct, now pinned by a test |
And, Equal |
were flat — fixed |
parseGroup / || splitting |
was flat — fixed |
Len |
a count, documented as the total across groups. Its one semantic use is Len()==0 = "constrains nothing", which stays correct because only the universal set can produce an empty group |
List |
iteration only — doc comment now warns against using it for semantics, naming both bugs it caused |
Specifiers.PreReleases |
a global policy hint (upstream's any(s.prereleases for s in self._specs)); does not decide what matches, so grouping cannot change it |
ContainsInstalled |
delegates to Contains |
NewSpecifiersFrom |
builds one AND-group, which is correct (upstream has no OR) — pinned so nobody "fixes" it |
The three structure-independent ones now have a test (TestFlattenedOperationsAreStructureIndependent) so the claim is asserted, not just asserted in prose.
⚠️ One premise in the review brief was wrong
The brief asked me to preserve "a leading or doubled comma is tolerated". It isn't — on this branch ",>=1" and ">=1,,<2" both error, because validConstraintRegexp requires the leading constraint. packaging 26.2 does accept both (it drops empty comma-split items), so this is a real, still-open divergence listed in rstudio/package-manager#19391 and not fixed in either PR.
I did not silently expand scope to fix it. The control test asserts the current behavior (rejected) with the divergence noted inline, which still does the control's job — it demonstrates the || change is orthogonal to comma handling. Happy to fix it as a follow-up; it is a widening, so low risk.
Red-then-green
Fixes stashed, tests run against the parent commit 12b4218:
--- FAIL: TestEmptyOrSegmentIsRejected (8 subtests: "An error is expected but got nil")
--- FAIL: TestEmptyOrSegmentCannotDisableAConstraint (">=1||" parsed, and then admitted 0.1)
--- FAIL: TestAndDistributesOverOrGroups
--- FAIL: TestAndDistributesBothSides
--- FAIL: TestEqualRespectsOrGroupBoundaries
--- FAIL: TestAndAgreesWithEqual
11 failing subtests
Green after: 28 subtests pass. The two functions green both ways are the preserved-behavior control and the Contains/Filter pin — neither is a bug repro, both are guards.
Blast radius
|| is not PEP 440 syntax — it is this package's R extension — so CRAN is the load-bearing corpus. || does not occur at all in 59,139 constraint occurrences of a real CRAN PACKAGES file, so the narrowing affects nothing real. The extraction pattern was positive-controlled: it flags the three malformed shapes and not the well-formed ">=1||<2".
Verification
build/vet/test/test -race under GOTOOLCHAIN=go1.25.0 and the local 1.26; gofmt -l . clean under both toolchains; golangci-lint v2.11.2 from the module root — 0 issues. Per-job CI on e93e425: lint success, build success.
#30 has been merged forward and re-verified — 1,613 conformance assertions still pass; per-job CI on its new head 68f1252: lint success, build success.
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) <noreply@anthropic.com>
…onformance Conflicts in version/specifier.go, both from parseGroup changing on both branches, resolved to keep BOTH intents: - parseGroup(vv, sanitizer, allowEmpty): #30's allowEmpty parameter AND #28's removal of the conf parameter. A member's pre-release policy is not the set's to stamp, and a comma-only group may only be universal when it is the entire input. - specifierCompatible keeps #30's versionJoin-based algorithm. #28's slice-bound guard is already present here and its comment is updated with what #28 established: the panic was reachable before versionSplit prepended the epoch, and the operand shapes that trigger it are the ones a hardening test stocked with "lolwat" never reaches. One conformance assertion updated: TestConformance_SetCombine expected And to keep duplicates. It now expects them to collapse, with the reason recorded -- upstream's len() of 2 is a pre-canonicalization artifact of a lazy cache, and str() is ">=1.0" under every ordering. The generator in the scratchpad was patched to match so a regeneration cannot reintroduce the old expectation. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
All eight reviewer findings addressed —
|
| total collected cases | 2,031 |
| from the 70 parametrized functions | 1,985 |
| from the 46 unparametrized ones | 46 |
scope cut (set relations + is_unsatisfiable) |
259, of which TestIsUnsatisfiable alone is 222 |
Reconciliation: 1,939 with VERSIONS unresolved + the 92 entries of VERSIONS from tests/test_version.py = 2,031; 2,031 − 46 = 1,985.
Root cause of my error, since it is the useful part: my counter only exec'd module-level ast.Assign nodes. TestIsUnsatisfiable's UNSATISFIABLE/SATISFIABLE are ClassVars declared inside the class, so every parametrize referring to them failed to evaluate and was silently counted as 1 instead of its real size. That is precisely the 222 that went missing, and it is why "~25" for the scope cut was ~10× low. The 1,735 also happened to equal the sum of three approximate buckets quoted beside it — an unreconciled number presented as exact.
What was accurate is now stated as what it is: 1,613 Go leaf subtests (1,649 with table parents), 358 failing pre-fix. The 188-case matching table was exact.
5. TestContainsAgreesWithFilterOfOne was tautological — deleted. Contains is len(Filter([]string{item})) > 0; the test asserted that expression against itself and could not fail. Its own comment conceded they "can never disagree", which should have been the tell. Replaced with TestContainsMatchesTheReference: 300 (specifier, policy, item) rows whose expected values were measured against packaging 26.2 — an oracle that is not the implementation.
Judged
2. And — I chose to dedupe, and withdrew the claim. The reviewer's lazy-cache observation is exactly right and I verified it:
c = SpecifierSet(">=1.0") & SpecifierSet(">=1.0")
len(c) -> 2 ; str(c) -> '>=1.0' ; len(c) -> 1
So the 2 is a transient pre-canonicalization artifact of _canonical_specs() — the one thing this port declares non-portable — and it makes the count depend on which method a caller invokes first. My "matches upstream" claim was anchored on that artifact and is withdrawn. str() is ">=1.0" under every ordering, so deduplication is upstream's settled behavior. Dedupe is canonical, so ">=1.0.0" and ">=1" collapse while "~=1.18.0" and "~=1.18" do not. Matching was never affected — a conjunction is idempotent.
6 and 7. And re-stamping and members reporting the set's policy — both fixed by making the container stop writing member state. Verified against upstream: list(SpecifierSet(">=1.0.dev1", prereleases=False))[0].prereleases is True while the set's is False, and __and__ leaves members at [False, False].
c.Filter admitting 1.5a1 where a.Filter did not does not reproduce with a single item — buffering offers the lone pre-release either way. The policy flip is real and is what I fixed (Auto → Include, member Exclude erased); the observable divergence needs two items so the preference engages. The test asserts the policy and the non-mutation directly rather than a Filter result that depends on that subtlety.
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 — so the singular constructor's policy still sticks, which is the boundary of the fix.
8. Zero-value Specifier — made consistent. All three spellings of "no constraint" now agree on every input class. 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, and there is a test for that.
The container → member stamping audit
The reviewer's note that 2, 6 and 7 share a cause is correct, and it is the same shape as the flat-bag bug in e93e425: state belonging to the member, flattened into the container. I swept every write.
Fixed (3 sites): newSpecifier via parseGroup · And's re-stamp · NewSpecifiersFrom's stamp.
Checked and clean (11 sites), named so the audit is evidence rather than assertion:
| site | why it is clean |
|---|---|
version.go cmpkey (k.pre = part.Infinity) |
writes the comparison key's field from the version's own pre segment; not container state, not a Specifier |
version.go normalizeLocal (segments[i]) |
rewrites the version's own local label |
filterGeneric (strs[i] = key(it)) |
derives a string from the caller's item via the caller's key func; touches no Specifier |
filterKeep, Specifiers.filterKeep, matchAll, groupMatches, allArbitraryMatch, applyPEP440Preference |
every write is to the boolean result mask; read-only over members |
dedupeSpecifiers |
copies member values into a fresh slice, writes no field |
orGroups |
returns existing groups or a synthetic empty one |
String / Len / List / Equal / canonicalGroupKeys / PreReleases |
read-only |
marker.Environment.With |
copies the receiver, writes only named fields on the copy; already covered by TestWithDoesNotMutateReceiver |
After the fix, exactly one line in non-test code sets a member's policy from a conf (specifier.go:408), and it is reachable with a non-zero conf only from NewSpecifier. TestNoConstructorStampsMemberPolicyFromSetPolicy pins the invariant across NewSpecifiers, NewRSpecifiers, NewSpecifiersWithSanitizer, OR-groups and the deprecated WithPreRelease, at all three policies.
Red-then-green
Fixes stashed, tests run against e93e425: 10 test functions, 22 subtests fail, including the real slice bounds out of range [:-1] panic and expected 1 / actual 2 for the dedupe. Green after.
Three functions pass both ways by design and are guards, not repros: TestAndDoesNotMutateItsOperands, TestZeroValueShortcutDoesNotSwallowRealSpecifiers, TestSingularConstructorPolicyStillSticks. TestContainsMatchesTheReference also passes both ways — it replaced a tautology with a real oracle, and the bugs it would have to catch live in And/List/zero-value paths rather than in Contains.
Verification
build/vet/test/test -race from the module root under GOTOOLCHAIN=go1.25.0 and local 1.26; gofmt -l . clean under both; golangci-lint v2.11.2 from the module root — 0 issues.
Per-job CI:
- Add the public specifier and marker API that PEP 440/508 conformance assertions need (rstudio/package-manager#19383) #28
015553d— build: success, lint: success - Port test_specifiers.py conformance tables and fix the six divergences they surface (rstudio/package-manager#19391) #30
2324367— build: success, lint: success (merged forward; 1,613 conformance assertions still pass)
Every corrected claim landed in the CHANGELOG as well as here, including the withdrawn len(... & ...) == 2 parity claim, the corrected counts, and the understated scope cut. Not merged.
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) <noreply@anthropic.com>
New medium fixed —
|
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) <noreply@anthropic.com>
🔴 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) <noreply@anthropic.com>
…onformance Brings in the v0.4.0 padding under-count and epoch regression fix. The specifier.go merge was clean: #28 now carries the same upstream _version_split / _left_pad port this branch already had, transplanted verbatim precisely so the two sides would be identical here. One CHANGELOG conflict, both branches having added to ### Breaking. Resolved by keeping BOTH entries with the padding one first, since a released module that serves versions pip excludes outranks a parse narrowing that measured 0 newly-rejected on real data. Conformance now 1,695 leaf subtests (1,613 + the 82-row padding/epoch oracle), 0 failing. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
🔴 F1 and F2 fixed —
|
| tree | divergences |
|---|---|
v0.4.0 (released) |
30 / 82 |
#28 before this fix |
30 / 82 (identical — padVersion is byte-identical) |
#30 |
0 / 82 |
All five of your reported rows reproduce, plus 25 more the multi-segment sweep found.
Which fix is load-bearing — you were right to ask
F1's fix alone takes 30 → 7, and it removes every epoch false-positive. So the under-padding, not the missing epoch prepend, is the proximate cause of ==0.0.0.* matching 1!1.0. The remaining 7 need the epoch prepend plus suffix-aware padding (==2.0.0.* vs 2rc1 and friends), because isDigist collected digits from anywhere in the slice rather than the prefix.
⚠️ Scoping correction: #30 already contained the complete fix
padVersion exists in v0.4.0 and #28; #30 had already replaced it with a direct port of upstream's _version_split / _version_join / _is_not_suffix / _numeric_prefix_len / _left_pad as part of the conformance work — measured at 0/82.
Rather than write a second, minimal fix, I transplanted that code verbatim into #28, so:
#28is now correct standalone — whichever of the two merges first,mainis right, with no broken window between merges;- the forward-merge was trivial, because both sides became identical (
specifier.gomerged clean); - there is one implementation of the algorithm, not a minimal patch in one PR and a port in the other.
A partial fix leaving 7 divergences would have repeated exactly the failure being criticised — "claims to fix the padding, but only for some gaps".
Blast radius vs v0.4.0
28,529 distinct specifier tokens (production PyPI + real CRAN; 1,926 of them wildcard or ~=), 24-version panel:
| parse acceptance | 0 newly accepted, 0 newly rejected (this is a matching fix) |
| match-vector changes | 2 tokens |
The two are ==2.0.* and !=2.0.*, both on the version 2rc1 — a pre-release interaction, not an epoch one, which is not what I first guessed and is why I checked rather than asserted. v0.4.0 had both backwards:
==2.0.* vs 2rc1 : v0.4.0 = false fixed = true packaging 26.2 = True
!=2.0.* vs 2rc1 : v0.4.0 = true fixed = false packaging 26.2 = False
Instrument validated: 7 of 8 synthetic multi-segment controls appended to the corpus flip. The 8th (==1!1.0.0.*) needs the version 1!1, which the panel does not carry — a panel gap, not a broken harness, and that row is covered directly by the oracle. !=7.0.0.* is reachable from arbitrary client input on POST /__api__/repos/:id/filter/packages.
The mis-framing is corrected in both places
You are right that this invalidates the dismissal carried through three documents. The "13 pairs" were described as "a separate, pre-existing epoch divergence"; both halves were false — the old module was correct, the change made them wrong, and the cause was padVersion itself. Corrected in the [0.1.0]-retrospective entry (which now says padVersion fixed 915 pairs and broke 13) and called out again in the new Breaking entry.
Why it survived a rewrite, a release and a changelog claim
⌈1/2⌉ == 1, so a 1-segment gap 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 held only for a gap of one. The new table's header says this explicitly so the next person does not add another 1-segment case and think it covers the arithmetic. There is also a direct leftPad test sweeping gaps 0–5, and a versionSplit test pinning the epoch component.
Changelog
New Breaking entry under ## [Unreleased], not softened: it opens with 🔴, says plainly that v0.4.0 shipped an under-padding bug and a new epoch regression, tells anyone on v0.4.0 to upgrade, and names the customer-visible !=7.0.0.* case and its PPM entry point.
Verification
Red-then-green: 30 of the 82 subtests fail on 244fc46. build/vet/test/test -race from the module root under GOTOOLCHAIN=go1.25.0 and local 1.26; gofmt -l . clean under both; golangci-lint v2.11.2 from the module root with exit codes read — config verify 0, run ./... 0, both worktrees.
Per-job CI, one push per branch:
- Add the public specifier and marker API that PEP 440/508 conformance assertions need (rstudio/package-manager#19383) #28
2864596— build: success, lint: success - Port test_specifiers.py conformance tables and fix the six divergences they surface (rstudio/package-manager#19391) #30
ab9405d— build: success, lint: success — conformance now 1,695 leaf subtests (1,613 + the 82 padding rows), 0 failing
⚠️ Not tagged, and it needs your decision
v0.4.0 is immutable and already consumed, so shipping this is a Breaking release. I have not tagged anything and the commit message says so explicitly. Both PRs are ready for the release decision. PPM's migration is unblocked by the code, but only once a version carrying it exists.
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) <noreply@anthropic.com>
The
|
| token | recognized as a suffix? | why |
|---|---|---|
dev1, a1, b1, rc1, post1 |
yes | listed directly |
alpha1, beta1 |
yes | incidentally, via the a and b entries |
c1, pre1, preview1, r1, rev1 |
no | not listed, and pre/preview/r/rev never match _prefix_regex so they stay whole |
That third row is why a one-token fix would have been wrong in a second way: alpha/beta are already handled by accident, so "add the missing aliases" would have been a no-op for them and a behavior change for the others.
Both proposed fixes make conformance worse — measured, not argued
I applied the structural fix experimentally and counted before reverting:
| variant | divergences over the 410-row sweep |
|---|---|
| as shipped | 0 |
add "c" to the suffix list |
moves ~=1.0c1 away from the reference |
| normalize the operand through the parser | 6 |
The structural fix breaks ~=1.0c1 plus ~=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 dot-separated forms do not match _prefix_regex un-normalized. So the "one predicate, one copy" instinct is right in general and wrong here specifically: specifierEqual legitimately normalizes, specifierCompatible legitimately must not, and that difference is upstream's.
What I delivered instead: the sweep, as you asked
Extended the oracle rather than writing a bespoke test — a 410-row sweep over 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, all expectations from packaging 26.2.
The count moved: conformance is now 2,105 leaf subtests (1,695 → 2,105), 0 failing.
⚠️ The part that matters most
Upstream's own test suite does not exercise c under ~=. I verified this: the ported conformance tables stay green under the broken variant. So porting upstream faithfully could never have caught a change here, and this sweep is the only thing holding the behavior.
Without it, the next person to read PEP 440 sees c missing from a list of aliases, adds it in good faith, and silently changes six alias forms with every test still passing. So isNotSuffix now carries a "DO NOT ADD C" note with the measurements and both failed fix attempts, plus a companion test pinning both alias tables so the coupling between them is visible rather than discovered.
Verification
build/vet/test/test -race from the module root under GOTOOLCHAIN=go1.25.0 and local 1.26; gofmt -l . clean under both; golangci-lint v2.11.2 from the module root with exit codes read — config verify 0, run ./... 0, both worktrees.
Per-job CI, one push per branch:
- Add the public specifier and marker API that PEP 440/508 conformance assertions need (rstudio/package-manager#19383) #28
0fc4eec— build: success, lint: success - Port test_specifiers.py conformance tables and fix the six divergences they surface (rstudio/package-manager#19391) #30
a3e5b9a— build: success, lint: success; conformance 2,105 subtests, 0 failing
Both worktrees clean, no stray files. Not merged, not tagged — the release train is yours. Both heads are ready for it.
#28 was merged to main as a SQUASH while this branch had already merged #28's branch, so the same work reached main by two routes and git had no common ancestor linking them. Five conflicts, all of that shape. Resolution: took THIS branch's side for all five, because this branch's content is main's content plus #30's own changes. Verified rather than assumed, three ways: - CHANGELOG.md diffs 198 insertions / 0 DELETIONS against main, which proves it contains every line main has; both sets of [Unreleased] entries survive, and the #28 landmarks (the DO-NOT-ADD-C note, the anchored single-constraint grammar, the 410-row sweep) are all still quoted in it. - `git diff origin/main -- version/specifier.go` shows ONLY #30's own changes: the [\s\v] whitespace class, the (?i) flags on validConstraintRegexp and singleConstraintRegexp, parseGroup's allowEmpty plus blank-comma-item dropping, and the >V post-release / local-version guards. No #28 content is re-added or reverted; the deletions are all lines #30 legitimately rewrites. - Every #28-derived file that #30 does not touch is byte-identical to main: alias_conformance_test.go, padding_conformance_test.go, member_policy_test.go, operand_hardening_test.go, prerelease_policy_test.go, specifier_query.go, prerelease.go, specifier_option.go, marker/environment.go and marker/partial_environment_test.go. And padVersion/isDigist -- the v0.4.0 bug -- are confirmed gone. Conformance is unchanged at 2,105 leaf subtests, 0 failing, which is the check that would have caught a bad resolution. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Closes rstudio/package-manager#19383. Unblocks rstudio/package-manager#19391 (the
test_specifiers.pyconformance tables), which lands separately.Why
Roughly 80% of
pypa/packaging'stest_specifiers.pycases 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 (Specifiers) was public, exposing justCheckandString.Measured on the 1,735 parametrized cases in upstream's
test_specifiers.py@4eb0753:str(), the 188-case matching tableprereleases(3-state),.filter(,.contains(with a string,.operator/.version,len()/iteration,Specifierequality,&,installed=to_rangeequivalence, pickling, internal caches, lazy constructionWhat this adds
Specifier— the exported singular specifier, withOperator(),Version(),Original(),String(),Check(),Contains(),ContainsVersion(),Filter(),FilterVersions(),PreReleases(),Equal(). Built withNewSpecifier, or read off a set withSpecifiers.List().PreReleases— a three-state policy (Auto/Include/Exclude) withWithPreReleases, which works both as aSpecifierOptionat construction and as aFilterOptionoverriding it for one call.Autois the zero value and derives the policy from the specifier per PEP 440, which a bool cannot express.Filter/Containson both types, implementing PEP 440 candidate selection.Containsis defined as "Filterof one item is non-empty", exactly as upstream defines it, so the two cannot disagree — and there is a cross-check test asserting that.NewSpecifier("===lolwat").Contains("lolwat")is now expressible. It was not before:Checktakes aversion.Versionandversion.Parse("lolwat")fails, so there was no way to pass the value in.FilterBy— upstream'skey=parameter, as a generic free function (Go methods cannot take type parameters).Specifiers.Len/List/Equal/And/ContainsInstalled,NewSpecifiersFrom.marker.Environment.With/Lookup,marker.VariableNames()— the partial-environment override seam.Two behavior changes that need a careful look
1.⚠️
WithPreRelease(true)no longer defeats the operator guardsIt set a flag on the
Versionunder test that madeVersion.IsPreRelease()reportfalsefor a version that plainly is a pre-release, which disabled the guards inspecifierLessThan/specifierGreaterThan. The observable effect was that<2matched2.0.dev1.Measured against
pypa/packaging26.2:The guard is part of what
<means, not a pre-release policy. The flag conflated candidate selection with matching — and PEP 440's rule is about selection: a pre-release does satisfy>=1.0, it is merely passed over while a final release is also available. The flag is removed, soIsPreRelease()is now a property of the version alone and aVersioncannot change identity depending on where it has been.TestVersion_CheckWithPreReleaseasserted{"2.0a1", "<2", true}and pinned the old behavior; it is corrected, with the oracle output quoted inline.WithPreReleaseis deprecated in favor ofWithPreReleases;true→Include,false→Auto(falsenever meant "exclude", it meant "no override").2.
Specifiers.String()is normalizedNewSpecifiers("< 2").String()was"< 2", now"<2", matching upstream.Requirement.String()is unaffected —internal/pep508'snormalizeSpecifierClausealready strips that whitespace before the string reachesversion.NewSpecifiers, so the two levels previously disagreed and now agree. Therequirement/conformance suite passes unchanged, which is the evidence.SpecifierSet(">=1,<2")→"<2,>=1"). Left as a documented divergence: the OR-of-ANDs shape this type carries for the R path (a || b) has no upstream counterpart to sort within, and reordering would churnRequirement.Stringfor no conformance gain.Deliberate scope cuts
Called out so review does not have to guess:
IsUnsatisfiable,IsSubset/IsSuperset/IsDisjointare not implemented. In packaging 26.2 these are backed by a whole interval/range subsystem (_to_ranges,_intersect_ranges,_LowerBound/_UpperBound). That is its own design exercise, not an accessor. ~25 upstream cases.validConstraintRegexpstill lacks the(?i)flagspecifierRegexphas, so==1.0A1is rejected while==1.0a1parses. That is one of #19391's listed divergences and lands there, where its blast radius gets measured — it widens what parses. TwoSpecifier.Equalrows are commented as blocked on it.Verification
Everything below was run from the module root, not scoped:
go build ./...,go vet ./...,go test -count=1 ./...,go test -race -count=1 ./...— all pass underGOTOOLCHAIN=go1.25.0(the version CI pins) and the local default 1.26.gofmt -l .clean under both Go 1.25's gofmt (the version the CI Format check actually runs) and the local default — checked separately because the two can disagree about blank lines in doc-comment lists.golangci-lint config verify+golangci-lint run ./...at CI's pinned v2.11.2 — 0 issues. (Note: passing an absolute path togolangci-lintreports a bogus "0 issues" alongside a typechecking error; it has to be run from the module root.)go list -deps ./...confirmspgregory.net/rapidis still absent from the non-test import graph and present in the test one.Oracle discipline: every expected value in the new tests was measured against
pypa/packaging26.2 with a throwaway script, not derived from the PEP text. That is what caught the===1.0.dev1pre-release autodetection (===gets no special case upstream — it tries to parse its operand like any other operator and only falls through to unresolved when that fails), which I had initially written the other way.The
MustParseregression test was verified to fail without the fix — I reintroduced the panic, watchedTestUnparseableOperandDoesNotPanicfail with a realpanic(...), then restored. Honest scope note is in the test file's header: those panics were not reachable through the public API before this change and are not now, but "unreachable" was a property of the callers, andSpecifier+Filterare new callers.🤖 Generated with Claude Code