Skip to content

Add the public specifier and marker API that PEP 440/508 conformance assertions need (rstudio/package-manager#19383) - #28

Merged
jonyoder merged 7 commits into
mainfrom
feat/19383-conformance-api
Aug 10, 2026
Merged

jonyoder merged 7 commits into
mainfrom
feat/19383-conformance-api

Conversation

@jonyoder

Copy link
Copy Markdown
Collaborator

Closes rstudio/package-manager#19383. Unblocks rstudio/package-manager#19391 (the test_specifiers.py conformance tables), which lands separately.

Why

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 (Specifiers) was public, exposing just Check and String.

Measured on the 1,735 parametrized cases in upstream's test_specifiers.py @ 4eb0753:

cases reachable before this PR?
Parse accept/reject, str(), the 188-case matching table ~330 yes
prereleases (3-state), .filter(, .contains( with a string, .operator/.version, len()/iteration, Specifier equality, &, installed= ~1,050 no
to_range equivalence, pickling, internal caches, lazy construction ~355 not portable to Go at all

What this adds

  • Specifier — the exported singular specifier, with Operator(), Version(), Original(), String(), Check(), Contains(), ContainsVersion(), Filter(), FilterVersions(), PreReleases(), Equal(). Built with NewSpecifier, or read off a set with Specifiers.List().
  • PreReleases — a three-state policy (Auto/Include/Exclude) with WithPreReleases, which works both as a SpecifierOption at construction and as a FilterOption overriding it for one call. Auto is the zero value and derives the policy from the specifier per PEP 440, which a bool cannot express.
  • Filter / 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 — and there is a cross-check test asserting that.
  • A string-operand query path. NewSpecifier("===lolwat").Contains("lolwat") is now expressible. It was not before: Check takes a version.Version and version.Parse("lolwat") fails, so there was no way to pass the value in.
  • FilterBy — upstream's key= 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 guards ⚠️

It set a flag on the Version under test that made Version.IsPreRelease() report false for a version that plainly is a pre-release, which disabled the guards in specifierLessThan/specifierGreaterThan. The observable effect was that <2 matched 2.0.dev1.

Measured against pypa/packaging 26.2:

Specifier("<2", prereleases=True).contains("2.0.dev1")  -> False
Specifier("<2").contains("2.0.dev1")                    -> False
Specifier("<2", prereleases=False).contains("2.0.dev1") -> False

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, so IsPreRelease() is now a property of the version alone and a Version cannot change identity depending on where it has been.

TestVersion_CheckWithPreRelease asserted {"2.0a1", "<2", true} and pinned the old behavior; it is corrected, with the oracle output quoted inline.

WithPreRelease is deprecated in favor of WithPreReleases; true → Include, false → Auto (false never meant "exclude", it meant "no override").

2. Specifiers.String() is normalized

NewSpecifiers("< 2").String() was "< 2", now "<2", matching upstream.

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, which is the evidence.

⚠️ Input order is still preserved. Upstream sorts its members (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 churn Requirement.String for no conformance gain.

Deliberate scope cuts

Called out so review does not have to guess:

  • IsUnsatisfiable, IsSubset/IsSuperset/IsDisjoint are 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.
  • validConstraintRegexp still lacks the (?i) flag specifierRegexp has, so ==1.0A1 is rejected while ==1.0a1 parses. That is one of #19391's listed divergences and lands there, where its blast radius gets measured — it widens what parses. Two Specifier.Equal rows are commented as blocked on it.
  • The conformance tables themselves are #19391, deliberately kept out so this PR is reviewable as API design rather than as bulk test data.

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 under GOTOOLCHAIN=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 to golangci-lint reports a bogus "0 issues" alongside a typechecking error; it has to be run from the module root.)
  • go list -deps ./... confirms pgregory.net/rapid is 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/packaging 26.2 with a throwaway script, not derived from the PEP text. That is what caught the ===1.0.dev1 pre-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 MustParse regression test was verified to fail without the fix — I reintroduced the panic, watched TestUnparseableOperandDoesNotPanic fail with a real panic(...), 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, and Specifier + Filter are new callers.

🤖 Generated with Claude Code

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>
@jonyoder

Copy link
Copy Markdown
Collaborator Author

RoboRev findings addressed — e93e425

All three findings were confirmed on this branch before fixing, and all three had 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 constraint

Confirmed, and the diagnosis holds including the regression claim. On this branch before the fix:

">=1||"      -> parses; groups=2; Check(0.1)=true   <-- below its own floor
"||>=1"      -> parses; groups=2; Check(0.1)=true
">=1||||<2"  -> parses; groups=3; Check(0.1)=true

Also confirmed on the R entry point, which is the one PPM uses. And confirmed it is a regression: at v0.4.0 an empty segment became a bare-version constraint of "" and errored.

Fixed as judged: 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 errors if asked to. Rejected shapes now include leading, trailing, doubled, whitespace-padded (">=1|| ||<2") and bare ("||", "||||").

MEDIUM — And: chose distribution

(==1.0||==2.0) AND <3.0 produced the single group ==1.0,==2.0,<3.0, which is unsatisfiable — measured, it rejected all three of 1.0, 2.0 and 5.0. Now (==1.0,<3.0) || (==2.0,<3.0).

Distribution rather than an error, because it is correct semantics and And is new API. It also turned up an edge the error path would have hidden — a cartesian product over a set with zero groups yields zero groups, silently discarding the other operand — so the universal set is now normalized to one empty group and is the identity of And in both positions. There is a test for that.

MEDIUM — Equal ignored group boundaries

Now compares the set of canonicalized AND-groups. Still blind to group order, within-group order, duplicates and pre-release policy; no longer blind to which members share a group. For a single-group set — everything a Python-style comma-separated string produces, so everything the conformance tables exercise — it reduces exactly to the previous behavior, and all 1,613 ported assertions still pass.

There is a test asserting And and Equal agree: the distributed result equals the hand-written "==1.0,<3.0||==2.0,<3.0" and does not equal the flattened "==1.0,==2.0,<3.0".

The full audit

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>
jonyoder added a commit that referenced this pull request Aug 10, 2026
…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>
@jonyoder

Copy link
Copy Markdown
Collaborator Author

All eight reviewer findings addressed — 015553d

I reproduced every one before changing anything. I agree with all eight, including the two where my own claim was the defect. Two carry a correction to the finding itself, noted below.

Must-fix

1. ~= panicked on a suffix-only operand — confirmed, fixed.

~= operand "dev1"   PANIC: slice bounds out of range [:-1]
~= operand "post1"  PANIC
~= operand "dev"    PANIC
~= operand "post"   PANIC
~= operand "lolwat"          -> false (no panic)
~= operand ""                -> false (no panic)
~= operand "not a version"   -> false (no panic)
~= operand "1.2.3.4.5-garbage" -> false (no panic)

The bottom four are the entire old operand list, which is the reviewer's point exactly: the table exercised every operator except the one that could crash, while the test's name and header claimed the whole shape class. Hardened, and the suffix-only shapes added, plus a dedicated test naming this as the one panic in the table that is a slice bound rather than a MustParse.

⚠️ Correction to the finding: the panic exists on #28 only. #30's rewrite of specifierCompatible ports upstream's _version_split, which prepends the epoch — so prefixElements is never empty there and the same probe reports "no panic" for all nine operands. Fixed in #28 anyway, because #28 can merge alone, and the merge-forward carries the enriched comment into #30's guard (whose "unreachable" note was true only by accident of versionSplit).

3. Three doc comments asserted ==1.0A1 behavior — confirmed, all three qualified. NewSpecifier("==1.0A1"), NewSpecifier("== 1.0A1") and NewSpecifier("==1.0+ABC") all return improper specifier. The reviewer is right that describing upstream in a Go method's doc comment reads as this API's contract. Version() and Equal() now use examples this package can actually produce (>= v1.0 , ==v1.0, ==0!1.0) with the case divergence called out and its issue named.

4. Counts corrected, with a reconciled denominator. The reviewer's figures are right and mine were wrong:

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].

⚠️ Correction to finding 6's repro: the specific 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:

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>
@jonyoder

Copy link
Copy Markdown
Collaborator Author

New medium fixed — bcf0481. My finding-8 fix was worse than the bug it fixed.

You're right, and the diagnosis is exact. I verified it before changing anything, on 015553d:

items = [1.0 1.1a1]
  zero Specifier    Auto      = [1.0 1.1a1]     <-- offers the pre-release
  NewSpecifiers("") Auto      = [1.0]           <-- correct
  zero Specifiers   Auto      = [1.0]

  zero Specifier    Exclude   = [1.0 1.1a1]     <-- override silently ignored
  NewSpecifiers("") Exclude   = [1.0]

So the fast path filled keep with true and returned before the policy logic, exactly as described. Third occurrence of the selection-versus-matching conflation in this change's history, and the most embarrassing one, because it was introduced by a fix while I was writing about that distinction two paragraphs above it.

The fix, and why both requirements hold together

You were right that they're compatible and shouldn't be traded. "Constrains nothing" is a claim on the matching axis only — the operator admits every version. Selection is a separate axis that still has to run.

A nil operator function is now a flag consumed by the existing loop rather than an early return:

  • Unparseable items ("lolwat") go through a new admitsUnparseable predicate, which returns true for a nil operator function or a matching ===. Finding 8's requirement is preserved: there is no version to classify as a pre-release, so the policy has nothing to act on.
  • Parseable items needed no change at all — Check's existing nil guard already returns true, so match becomes true and the item then flows through the normal buffering and policy logic.

Result, all four spellings agreeing on both axes:

  zero Specifier / zero Specifiers / NewSpecifiers("") / set-with-zero-member
  Filter(["1.0","1.1a1"])                    = [1.0]      (final preferred)
  Filter(["1.1a1"])                          = [1.1a1]    (lone pre-release offered)
  Filter(["1.0","1.1a1"], Exclude)           = [1.0]      (override honored)
  Filter(["1.1a1"], Exclude)                 = []         (can empty the result)
  Contains("lolwat")                         = true       (finding 8 preserved)

A fourth spelling was also broken

Re-checking the others as you asked turned up one more in the same family: allArbitraryMatch re-tested op == "===" inline instead of sharing the predicate, so

NewSpecifiersFrom([]Specifier{{}}).Contains("lolwat")  ->  false
Specifier{}.Contains("lolwat")                         ->  true

Two copies of one predicate in two places is how they drifted. There is now a single admitsUnparseable used by both call sites.

The test whose absence let this through

TestConstrainsNothingAgreesOnBothAxes asserts all four spellings against each other on:

  • matching axis — every item admitted, including three unparseable classes;
  • selection axis — final preferred over pre-release; lone pre-release offered; each explicit policy honored, including that Exclude can empty the result;
  • Contains across eight input classes.

Driven through filterGeneric against the Filterer interface so one loop covers a Specifier and three Specifiers shapes uniformly.

⚠️ One clarification on your instruction. You asked that "a parsed bare version must land on the same answer as the zero-value Specifier". It must not, and I did not assert that: NewSpecifier("2.0") is a real constraint equivalent to ==2.0, not a spelling of "constrains nothing". It has an empty operator string but a non-nil operator function, which is exactly why the zero-value shortcut keys on the function rather than the string — gating on the string would have turned every bare-version constraint into a no-op, and PPM's R path depends on bare versions. TestZeroValueShortcutDoesNotSwallowRealSpecifiers pins that separately. The four genuine spellings are the zero Specifier, the zero Specifiers, NewSpecifiers(""), and a set holding a zero member.

Doc comments

filterKeep's comment now states which axis "constrains nothing" applies to and records the specific failure the short-circuit produced, so the next reader doesn't reintroduce it as an optimization. admitsUnparseable carries the same axis note, including why matching and selection coincide for an unparseable string and why that coincidence must not be generalized.

Red-then-green

4 subtests fail on 015553d:

zero Specifier must hold back the pre-release when a final release is available
zero Specifier must honor PreReleasesExclude
set with zero member must agree on Contains("lolwat")
set with zero member must admit every item

Green after. The lone-pre-release subtest passes both ways and is a guard, not a repro.

Verification

build/vet/test/test -race from the module root under GOTOOLCHAIN=go1.25.0 and local 1.26; gofmt -l . clean under both toolchains; golangci-lint v2.11.2 from the module root with the exit code read explicitly — config verify 0, run ./... 0, on both worktrees.

Per-job CI, one push per branch so nothing was cancelled:

CHANGELOG updated with both defects and the axis distinction. Not merged.

jonyoder and others added 2 commits August 10, 2026 13:45
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>
jonyoder added a commit that referenced this pull request Aug 10, 2026
…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>
@jonyoder

Copy link
Copy Markdown
Collaborator Author

🔴 F1 and F2 fixed — 2864596. Both confirmed against the released v0.4.0.

Your mechanism for F1 is exactly right, and I verified both against v0.4.0 itself rather than only the parent commit, since "what changes relative to what I have" is the question anyone on v0.4.0 is asking.

Measured: v0.4.0 diverges on 30 of 82 oracle rows

I built an 82-row table sweeping gaps of 1–4 in both directions, with zero and non-zero tails, pre-release segments and epochs, every expected value from packaging 26.2. Then ran it against three trees:

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:

  • #28 is now correct standalone — whichever of the two merges first, main is right, with no broken window between merges;
  • the forward-merge was trivial, because both sides became identical (specifier.go merged 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. ⚠️ The small real-world count reflects that multi-segment-gap wildcards barely occur in real constraint data — not that the bug was harmless, since !=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:

⚠️ 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>
@jonyoder

Copy link
Copy Markdown
Collaborator Author

The ~=1.0c1 asymmetry is conformance, not a bug — 0fc4eec

I verified before fixing, as asked, and the measurement says there is nothing to fix. packaging 26.2 has 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").

Where the asymmetry actually comes from

A mismatch between two upstream tables, not from this port:

  • _prefix_regex = ([0-9]+)((?:a|b|c|rc)[0-9]+) — includes c, so 0c1 splits into 0 + c1;
  • _is_not_suffix — excludes c, so the resulting c1 counts as release rather than suffix, and the derived prefix is one component narrower.

You asked me to check the whole family rather than one token, and that is what showed c is the only alias in the gap. The family splits three ways, not two, because the check is a prefix match:

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:

Both worktrees clean, no stray files. Not merged, not tagged — the release train is yours. Both heads are ready for it.

@jonyoder
jonyoder merged commit 9891ace into main Aug 10, 2026
2 checks passed
@jonyoder
jonyoder deleted the feat/19383-conformance-api branch August 10, 2026 18:16
jonyoder added a commit that referenced this pull request Aug 10, 2026
#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>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant