Skip to content

feat(pnpr): resolve Python projects through the install accelerator - #14613

Merged
zkochan merged 13 commits into
mainfrom
python-resolve
Sep 6, 2026
Merged

zkochan merged 13 commits into
mainfrom
python-resolve

Conversation

@zkochan

@zkochan zkochan commented Sep 6, 2026 •

Copy link
Copy Markdown
Member

Summary

/-/pnpr/v0/resolve now reads "ecosystem": "pypi" beside npm and Cargo, so a pnpm install with pnprServer set resolves its Python dependencies server-side. This is the second half of the accelerator item in #14599; the Cargo half landed in #14607.

Python is where a server-side resolve earns the most. Reading what a distribution requires means reading a wheel's METADATA, which lives inside the wheel, so a client resolving alone downloads whole wheels for versions it then rejects. pnpr reads the metadata file the index publishes beside each wheel (PEP 658, either field spelling), falls back to the wheel itself only for an index that publishes none, and keeps what it read for every client that follows.

The resolver moved out of the CLI. It lived in pnpm/crates/cli/src/python/, where it could only run beside an interpreter: the pubgrub provider read a registry that downloads wheels and asks the bundled host.py what they require. A registry server can do neither. pnpm-python-resolver now owns what resolution decides — which wheel of a version a target installs, how a requirement's markers and extras constrain a solution, what a wheel's METADATA says, what pylock.toml records — and every fetch stays with whoever can do it. step runs one pubgrub pass and either solves the project or names the one distribution or wheel it still needs, which is the shape the CLI's loop already had. The CLI keeps everything interpreter-shaped: probing it, reading a downloaded wheel through host.py, ingesting wheels into the store, building the environment.

No interpreter runs on the server. The marker environment and the wheel tags travel in the request as the client's own, and pnpr matches wheels against them without running any Python. The lockfile records both, as it already did, so it is only ever reused for the interpreter it was resolved for.

The client verifies rather than trusts. A returned lockfile has to record the inputs this install asked about; its wheels are downloaded and checked against the digests the index published; and the project is re-solved against the metadata of the wheels that actually arrived. That is the same path an existing pylock.toml already takes, so a server answering with someone else's project, or with a package the requirements do not reach, fails the install rather than installing anything. Server-side, a metadata file or wheel that does not match the digest the index published is refused before it reaches the solver.

Boundaries match the Cargo path. The index origin must be on the route allowlist; every read is classified by the project it is for, so an upstream's per-project rules decide the credential and the cache namespace; a cold read is fetched once across concurrent resolves; and per-resolve caps bound the distributions, the metadata reads, each response, and the bytes one request holds. A server that does not advertise pypi leaves the client resolving locally, and --offline skips the server entirely.

Not in this PR. The lockfile that comes back names the index's own wheel URLs rather than URLs routed through pnpr, so a private index still has to be reachable by the client with its own credentials — the same shape the Cargo path has, and worth solving for both at once. Nothing here changes how a Python environment is built: the client downloads and installs exactly as before.

Squash Commit Body

Resolution lived inside the CLI, where it could only run beside an
interpreter: the pubgrub provider read a registry that downloads wheels
and asks `host.py` what they require. A registry server resolving on a
client's behalf can do neither, so the rules move to
`pnpm-python-resolver` and the fetching stays with whoever can do it.
`step` runs one pubgrub pass and either solves the project or names the
one distribution or wheel it still needs, which is the shape the CLI's
loop already had.

`POST /-/pnpr/v0/resolve` reads `"ecosystem": "pypi"` beside npm and
Cargo. The body carries the project's requirements and the interpreter
they are for; the answer is the `pylock.toml` the client writes. pnpr
reads the metadata file an index publishes beside each wheel (PEP 658,
either spelling), falls back to the wheel itself only for an index that
publishes none, and keeps what it read for every client that follows —
so the client stops downloading whole wheels for versions a resolution
then rejects.

The client verifies the answer rather than trusting it: the lockfile has
to record the inputs this install asked about, its wheels are downloaded
and checked against the index's digests, and the project is re-solved
against the metadata of what actually arrived. Server-side, a read that
does not match the digest the index published is refused before it
reaches the solver.

Reads are bounded and scoped as the Cargo path's are: an allowlisted
index origin, per-project route classification, single-flighted cold
reads, and caps on the distributions, metadata reads, each response, and
the bytes one request holds. Asking a server which ecosystems it
resolves is one memo for both ecosystems now, keyed by server and
ecosystem.

Related to pnpm/pnpm#14599.

Checklist

  • I checked the referenced issue and verified that none of the PRs
    already linked to it solves it.
  • New features are implemented only in the Rust pnpm v12 CLI. Bug fixes
    are implemented in every affected version.
  • Added a changeset (pnpm changeset) if this PR changes any published
    package. Keep it short and written for pnpm users — it becomes a release note.
  • Added or updated tests.
  • Updated the documentation if needed.

Written by an agent (Claude Code, claude-opus-5).


View with [code]smith Autofix with [code]smith
Need help on this PR? Tag @codesmith-bot with what you need. Autofix is disabled.

Summary by CodeRabbit

  • New Features

    • Added Python dependency resolution through configured pnpr servers.
    • Python resolution supports PyPI metadata, compatible wheels, lockfiles, and dependency requirements.
    • pnpr servers now advertise and handle Python resolution alongside npm and Cargo.
    • Installations fall back to local Python resolution when server support is unavailable or offline.
    • Python resolution validates indexes, metadata, compatibility, integrity, and lockfile inputs.
    • Published metadata can be used without downloading wheels solely for inspection.
  • Documentation

    • Updated pnpr documentation to describe Python resolution and supported ecosystems.

@coderabbitai

coderabbitai Bot commented Sep 6, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Team

Run ID: e31fae51-71a6-4213-a041-5e34759c5e08

📥 Commits

Reviewing files that changed from the base of the PR and between 4833b6d and 221a53e.

📒 Files selected for processing (5)
  • pnpm/crates/cli/src/python/tests.rs
  • pnpr/crates/pnpr/src/resolver/pypi.rs
  • pnpr/crates/pnpr/tests/pypi_resolve.rs
  • pnpr/crates/pnpr/tests/server.rs
  • pnpr/npm/pnpr/README.md

Included review availability: Your plan provides up to 10 included reviews per hour; 2 remain after this review.


📝 Walkthrough

Walkthrough

Changes

Python resolution through pnpr

Layer / File(s) Summary
Shared Python resolver
Cargo.toml, pnpm/crates/python-resolver/*
Adds shared candidate parsing, wheel metadata parsing, lockfile types, package state, and PubGrub-based resolution.
pnpm client integration
pnpm/crates/cli/*, pnpm/crates/pnpr-client/*
Uses the shared resolver, negotiates PyPI support, submits remote resolution requests, validates returned lockfiles, and preserves local fallback.
pnpr PyPI endpoint
pnpr/crates/pnpr/*, pnpr/npm/pnpr/README.md, .changeset/*
Adds PyPI resolution, index and metadata caching, route and digest validation, terminal lockfile frames, integration tests, and documentation.

Estimated code review effort: 5 (Critical) | ~120 minutes

Merge Risk: ⚪ Minimal · up to 221a5

Python dependency resolution can now use pnpr while retaining local fallback and client-side wheel verification. No concrete merge-blocking risk remains in the supplied evidence.

Sequence Diagram(s)

sequenceDiagram
  participant pnpm
  participant PnprClient
  participant pnpr
  participant PyPIIndex
  participant PythonResolver
  pnpm->>PnprClient: check PyPI capability
  PnprClient->>pnpr: POST Python resolve request
  pnpr->>PyPIIndex: fetch project pages and metadata
  PyPIIndex-->>pnpr: return candidates and metadata
  pnpr->>PythonResolver: resolve Python requirements
  PythonResolver-->>pnpr: return lockfile
  pnpr-->>PnprClient: return terminal lockfile frame
  PnprClient-->>pnpm: return validated lockfile
Loading
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch python-resolve

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@qodo-code-review

Copy link
Copy Markdown

PR Summary by Qodo

Resolve Python dependencies through pnpr

✨ Enhancement 🧪 Tests 📝 Documentation 🕐 40+ Minutes

Grey Divider

AI Description

• Adds server-side PyPI resolution using cached PEP 658 metadata.
• Extracts reusable Python resolution rules from the CLI.
• Verifies returned lockfiles, downloaded wheels, and resolved dependency graphs client-side.
Diagram

sequenceDiagram
    actor User
    participant CLI as pnpm CLI
    participant Client as pnpr Client
    participant Server as pnpr Resolver
    participant Core as Python Resolver
    participant Cache as Metadata Cache
    participant Index as PyPI Index
    User->>CLI: pnpm install
    CLI->>Client: Negotiate PyPI support
    Client->>Server: Resolve requirements and target
    loop Until solved
        Server->>Core: Run resolution step
        Core-->>Server: Request candidates or metadata
        Server->>Cache: Read cached document
        alt Cache miss
            Server->>Index: Fetch index or metadata
            Server->>Cache: Store verified document
        end
    end
    Server-->>Client: Return pylock document
    Client-->>CLI: Proposed lockfile
    CLI->>Index: Download locked wheels
    CLI->>Core: Re-solve and validate
Loading
High-Level Assessment

The following are alternative approaches to this PR:

1. Duplicate client and server resolvers
  • ➕ Allows each runtime to optimize its own fetching and data model
  • ➕ Avoids introducing a shared workspace crate
  • ➖ Risks behavioral drift between proposed and verified solutions
  • ➖ Duplicates marker, extras, wheel-selection, and lockfile logic
  • ➖ Makes security fixes harder to apply consistently
2. Trust server-produced lockfiles
  • ➕ Reduces client work and avoids a second resolution pass
  • ➕ Simplifies the installation flow
  • ➖ Allows incorrect or unrelated server answers to influence installation
  • ➖ Weakens verification against downloaded wheel metadata
  • ➖ Creates a stronger trust requirement for pnpr deployments

Recommendation: Keep the shared step-based resolver and client-side verification implemented by this PR. Separating pure resolution decisions from caller-owned fetching lets the CLI and server use different metadata sources without duplicating semantics, while re-solving downloaded wheels preserves the existing trust boundary.

Files changed (37) +2423 / -521

Enhancement (10) +1005 / -34
pnpr_ecosystems.rsMemoize pnpr support by server and ecosystem +43/-0

Memoize pnpr support by server and ecosystem

• Adds process-lifetime capability negotiation shared by Cargo and Python, including cached failures for concurrent roots.

pnpm/crates/cli/src/pnpr_ecosystems.rs

python.rsOffload Python resolution and verify responses +80/-12

Offload Python resolution and verify responses

• Negotiates PyPI support, requests server-side resolution, and falls back locally when unavailable or offline. Returned lockfiles must match requested inputs and are revalidated against downloaded wheels before installation.

pnpm/crates/cli/src/python.rs

lib.rsAdd the pnpr PyPI resolve client +89/-17

Add the pnpr PyPI resolve client

• Introduces PyPI request options, ecosystem negotiation constants, and typed lockfile response parsing. Cargo and Python now share bounded single-terminal-frame handling.

pnpm/crates/pnpr-client/src/lib.rs

candidates.rsSelect installable wheels from Simple API pages +150/-0

Select installable wheels from Simple API pages

• Parses PEP 691 pages, ranks compatible wheels, filters yanked or interpreter-incompatible files, and captures PEP 658/714 metadata digests. It also centralizes wheel identity, URL, and requirement validation.

pnpm/crates/python-resolver/src/candidates.rs

metadata.rsParse Python wheel METADATA documents +66/-0

Parse Python wheel METADATA documents

• Adds RFC 822-style parsing for distribution identity, dependencies, extras, and Python version constraints, including continued fields.

pnpm/crates/python-resolver/src/metadata.rs

packages.rsModel incremental resolution knowledge +36/-0

Model incremental resolution knowledge

• Adds shared candidate and package stores for known distribution versions and fetched wheel metadata.

pnpm/crates/python-resolver/src/packages.rs

resolver.rsAdvertise and dispatch PyPI resolution +22/-5

Advertise and dispatch PyPI resolution

• Adds Python resolver modules, scoped index caches and locks, PyPI capability advertisement, and request dispatch. It also shares compact diagnostic formatting across ecosystems.

pnpr/crates/pnpr/src/resolver.rs

protocol.rsDefine the PyPI resolve request +21/-0

Define the PyPI resolve request

• Adds the requirements, client interpreter target, index URL, and project Python constraint accepted by the shared resolve endpoint.

pnpr/crates/pnpr/src/resolver/protocol.rs

pypi.rsImplement secure cached PyPI resolution +485/-0

Implement secure cached PyPI resolution

• Adds policy-aware Simple API and metadata fetching, PEP 658 preference, wheel fallback, digest verification, scoped caching, and resource budgets. It drives the shared resolver until producing a pylock document.

pnpr/crates/pnpr/src/resolver/pypi.rs

wire.rsSerialize Python terminal frames +13/-0

Serialize Python terminal frames

• Adds the NDJSON done frame carrying a serialized Python lockfile with safe error fallback.

pnpr/crates/pnpr/src/resolver/wire.rs

Refactor (11) +456 / -457
cargo_deps.rsShare pnpr ecosystem negotiation +8/-38

Share pnpr ecosystem negotiation

• Replaces Cargo-specific server capability memoization with the reusable ecosystem negotiation helper.

pnpm/crates/cli/src/cargo_deps.rs

lib.rsRegister shared ecosystem negotiation module +1/-0

Register shared ecosystem negotiation module

• Adds the CLI module used to memoize pnpr ecosystem support checks.

pnpm/crates/cli/src/lib.rs

package_specifier.rsUse shared Python requirement parsing +1/-1

Use shared Python requirement parsing

• Routes Python package specifier validation through the extracted resolver crate.

pnpm/crates/cli/src/package_specifier.rs

host.rsRepresent interpreters with shared resolution targets +8/-3

Represent interpreters with shared resolution targets

• Embeds the shared marker environment and ordered wheel tags into interpreter reports while retaining installation-specific metadata.

pnpm/crates/cli/src/python/host.rs

manifest.rsCentralize Python requirement parsing +2/-8

Centralize Python requirement parsing

• Removes the CLI-local parser and imports the shared direct-URL-rejecting parser.

pnpm/crates/cli/src/python/manifest.rs

registry.rsSeparate resolution data from installed wheels +35/-97

Separate resolution data from installed wheels

• Uses shared candidate parsing and package state while retaining full interpreter wheel reports for installation. Downloaded wheels populate both resolution metadata and store-specific records.

pnpm/crates/cli/src/python/registry.rs

resolver.rsDrive the shared step-based resolver +23/-231

Drive the shared step-based resolver

• Replaces the CLI-local PubGrub provider with a loop that satisfies shared candidate and metadata requests. Locked solution validation now delegates to the shared crate.

pnpm/crates/cli/src/python/resolver.rs

lib.rsExpose shared Python resolution primitives +32/-0

Expose shared Python resolution primitives

• Defines the crate boundary and exports candidate, metadata, package, lockfile, and step-based resolution APIs.

pnpm/crates/python-resolver/src/lib.rs

lockfile.rsOwn Python target and lockfile semantics +57/-38

Own Python target and lockfile semantics

• Moves target, input, locked package, wheel integrity, lockfile construction, and lockfile seeding into the shared crate.

pnpm/crates/python-resolver/src/lockfile.rs

resolve.rsExtract step-based PubGrub resolution +277/-0

Extract step-based PubGrub resolution

• Moves marker, extras, prerelease, and interpreter constraint handling into a fetch-independent provider. Exposes incremental steps plus exact locked-graph validation.

pnpm/crates/python-resolver/src/resolve.rs

cargo.rsShare package-aware upstream routing +12/-41

Share package-aware upstream routing

• Replaces the Cargo-specific route adapter with a reusable canonical package route used by Cargo and Python.

pnpr/crates/pnpr/src/resolver/cargo.rs

Tests (7) +858 / -25
tests.rsUpdate Cargo negotiation failure assertion +1/-1

Update Cargo negotiation failure assertion

• Adjusts the concurrent handshake test for the shared helper's error wording.

pnpm/crates/cli/src/cargo_deps/tests.rs

tests.rsTest CLI pnpr Python negotiation +154/-0

Test CLI pnpr Python negotiation

• Covers successful server offloading, local fallback when PyPI is unsupported, and offline avoidance of pnpr requests.

pnpm/crates/cli/src/python/tests.rs

tests.rsTest shared Python resolution behavior +240/-0

Test shared Python resolution behavior

• Covers metadata parsing, target wheel selection, candidate filtering, metadata advertisements, incremental resolution, and unsatisfiable requirements.

pnpm/crates/python-resolver/src/tests.rs

tests.rsTest PyPI resolver utility boundaries +76/-0

Test PyPI resolver utility boundaries

• Covers wheel METADATA extraction, malformed wheels, index URL normalization and validation, and request byte budgets.

pnpr/crates/pnpr/src/resolver/pypi/tests.rs

cargo_resolve.rsRemove obsolete PyPI rejection coverage +0/-23

Remove obsolete PyPI rejection coverage

• Deletes the test asserting that pnpr rejects PyPI resolution now that the ecosystem is supported.

pnpr/crates/pnpr/tests/cargo_resolve.rs

pypi_resolve.rsExercise end-to-end PyPI resolution +386/-0

Exercise end-to-end PyPI resolution

• Tests PEP 658 metadata resolution, wheel fallback, cache reuse, digest mismatch rejection, unsatisfiable graphs, route allowlists, and direct-URL rejection.

pnpr/crates/pnpr/tests/pypi_resolve.rs

server.rsAdvertise PyPI in resolver capabilities +1/-1

Advertise PyPI in resolver capabilities

• Updates the server handshake expectation to include the newly supported PyPI ecosystem.

pnpr/crates/pnpr/tests/server.rs

Documentation (2) +20 / -5
python-resolution-through-pnpr.mdAnnounce accelerated Python resolution +6/-0

Announce accelerated Python resolution

• Adds minor release notes for pnpr and pacquet describing server-side Python resolution, local fallback, and client verification.

.changeset/python-resolution-through-pnpr.md

README.mdDocument Python install acceleration +14/-5

Document Python install acceleration

• Explains server-side Python metadata resolution, shared caching, and the expanded resolver-disable flag behavior.

pnpr/npm/pnpr/README.md

Other (7) +84 / -0
Cargo.lockLock the shared Python resolver dependencies +19/-0

Lock the shared Python resolver dependencies

• Registers the new resolver crate and connects it to the CLI, pnpr client, and pnpr server dependency graphs.

Cargo.lock

Cargo.tomlRegister the Python resolver workspace crate +1/-0

Register the Python resolver workspace crate

• Adds the new internal Python resolver crate to workspace dependencies.

Cargo.toml

Cargo.tomlDepend on the shared Python resolver +1/-0

Depend on the shared Python resolver

• Makes shared Python resolution types and behavior available to the CLI.

pnpm/crates/cli/Cargo.toml

Cargo.tomlAdd Python resolver types to pnpr client +1/-0

Add Python resolver types to pnpr client

• Adds the shared crate required for Python targets and lockfile response types.

pnpm/crates/pnpr-client/Cargo.toml

Cargo.tomlDefine the shared Python resolver crate +24/-0

Define the shared Python resolver crate

• Creates the internal crate with PEP parsing, PubGrub, serialization, integrity, and URL dependencies.

pnpm/crates/python-resolver/Cargo.toml

Cargo.tomlAdd server-side Python resolution dependencies +3/-0

Add server-side Python resolution dependencies

• Adds the shared resolver and PEP 440/508 libraries to the pnpr server.

pnpr/crates/pnpr/Cargo.toml

package_route.rsAdd canonical package route binding +35/-0

Add canonical package route binding

• Introduces a reusable upstream hook that applies package-specific authorization and cache scoping to package-blind fetch helpers.

pnpr/crates/pnpr/src/resolver/package_route.rs

@greptile-apps

greptile-apps Bot commented Sep 6, 2026 •

Copy link
Copy Markdown
Contributor

Confidence Score: 5/5

The PR appears safe to merge; the latest change closes the remaining stale-cache case without introducing a new actionable issue.

All previous findings are resolved, dismissed with a correct concession, or manually resolved, and the changes since the previous review correctly bind fallback metadata to the required SHA-256 wheel digest.

Reviews (7): Last reviewed commit: "docs(pnpr): say what the Python resolver..." | Re-trigger Greptile

Comment thread pnpr/crates/pnpr/src/resolver/pypi.rs Resolved
Comment thread pnpr/crates/pnpr/src/resolver/pypi.rs Resolved
Comment thread pnpm/crates/cli/src/python.rs Resolved
@qodo-code-review

qodo-code-review Bot commented Sep 6, 2026 •

Copy link
Copy Markdown

Code Review by Qodo

🐞 Bugs (0) 📘 Rule violations (0) 📜 Skill insights (0)

Grey Divider


Action required

1. Large wheels exhaust server resources ✓ Resolved 🐞 Bug ➹ Performance
Description
read_bytes clones every fetched body into CachedDocument, whose ordinary Vec<u8> is then
serialized by serde_json as a decimal-number array. A permitted 256-MiB fallback wheel can
therefore coexist with two binary copies and roughly 0.5–1.1 GiB of JSON while also producing an
exceptionally large cache write.
Code

pnpr/crates/pnpr/src/resolver/pypi.rs[R325-327]

+        let body = self.hold(kind, response.body)?;
+        Self::store(cache_path, CachedDocument { url: source.to_string(), body: body.clone() })
+            .await;
Relevance

●● Moderate

Large-response memory amplification is plausible, but no close precedent establishes team treatment
of this performance concern.

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
Fallback wheels may be 256 MiB, and the response body is cloned before cache serialization.
CachedDocument derives normal Serde behavior over Vec<u8>, while serde_json::to_vec creates a
separate JSON numeric-array buffer before the atomic write; unlike this path, the analogous Cargo
cache writes already-serialized text directly.

pnpr/crates/pnpr/src/resolver/pypi.rs[70-72]
pnpr/crates/pnpr/src/resolver/pypi.rs[323-328]
pnpr/crates/pnpr/src/resolver/pypi.rs[378-386]
pnpr/crates/pnpr/src/resolver/pypi.rs[391-397]
pnpr/crates/pnpr/src/resolver/cargo.rs[350-360]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
Fallback wheel bodies are cloned and serialized as JSON arrays of byte values, causing severe memory and disk amplification for large valid wheels. The 256-MiB wheel limit makes peak allocations and cache files large enough to threaten server availability.

## Issue Context
Use a compact binary cache representation, stream the cache write where possible, or avoid caching whole fallback wheels after extracting their metadata. Preserve the final redirected source URL without wrapping raw wheel bytes in ordinary JSON serialization.

## Fix Focus Areas
- pnpr/crates/pnpr/src/resolver/pypi.rs[70-72]
- pnpr/crates/pnpr/src/resolver/pypi.rs[323-328]
- pnpr/crates/pnpr/src/resolver/pypi.rs[378-386]
- pnpr/crates/pnpr/src/resolver/pypi.rs[391-397]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


2. Crafted targets can stall the server ✓ Resolved 🐞 Bug ⛨ Security
Description
PypiResolveRequest accepts an unconstrained target tag list, and candidates_from_page compares
every advertised wheel against that entire caller-supplied list. An authenticated caller can combine
many tags with a large Simple API page to force multiplicative parsing and string allocation before
the distribution or metadata-read limits apply.
Code

pnpm/crates/python-resolver/src/candidates.rs[75]

+        let Some((wheel_name, version, rank)) = wheel_identity(&file.filename, &target.tags)?
Relevance

●● Moderate

Security resource-exhaustion concern is plausible, but no closely matching accepted or rejected
precedent was found.

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
The request schema places no bounds on target, whose tags are supplied by the remote caller. Each
file in the up-to-32-MiB project page calls wheel_identity, and that function linearly scans and
splits every supplied tag until it finds a match, yielding work proportional to files multiplied by
tags; the resolve route otherwise inherits the broad 100-MiB server body limit.

pnpr/crates/pnpr/src/resolver/protocol.rs[56-69]
pnpr/crates/pnpr/src/resolver/pypi.rs[54-77]
pnpm/crates/python-resolver/src/candidates.rs[71-76]
pnpm/crates/python-resolver/src/candidates.rs[110-122]
pnpr/crates/pnpr/src/server/routing.rs[137-145]
pnpr/crates/pnpr/src/server/routing.rs[204-211]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
PyPI resolve requests permit an unbounded target tag list, while every index wheel scans that list and repeatedly splits tag strings. This permits an authenticated caller to create multiplicative CPU and allocation work from one request.

## Issue Context
The existing distribution, metadata-read, and upstream-byte limits do not constrain request fields or the number of tag comparisons performed per page. Add defensible request/tag limits and pre-parse the target tags into a representation that avoids repeated splitting for every wheel.

## Fix Focus Areas
- pnpr/crates/pnpr/src/resolver/protocol.rs[56-69]
- pnpr/crates/pnpr/src/resolver/pypi.rs[87-110]
- pnpm/crates/python-resolver/src/candidates.rs[71-76]
- pnpm/crates/python-resolver/src/candidates.rs[110-122]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools



Remediation recommended

3. Package updates fail until cache expiry ✓ Resolved 🐞 Bug ☼ Reliability ⭐ New
Description
metadata keys cached documents only by route scope and metadata URL, then returns cache hits
without checking the current candidate digest. When an index republishes the same URL with a new
metadata or wheel digest, the server solves from the old document and the client's wheel
revalidation rejects that result until the cache expires.
Code

pnpr/crates/pnpr/src/resolver/pypi.rs[R281-284]

+        let cache_path = self.cache_path(&auth, &metadata_url(&wheel_url));
+        if let Some(cached) = self.cached(&cache_path).await {
+            let document = self.hold("metadata", cached.body)?;
+            return parse_metadata(&document, name, version, &candidate.wheel.name);
Relevance

●●● Strong

Recent accepted precedent requires validating fetched documents before caching; stale digest reuse
similarly bypasses current integrity checks.

PR-#14598

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
The cache path contains the metadata URL but no digest, and both cache-hit branches return the
stored body directly. Only fresh metadata or wheel reads are checked against the candidate's current
digest, while the resulting metadata directly feeds resolution and lockfile construction.

pnpr/crates/pnpr/src/resolver/pypi.rs[276-305]
pnpr/crates/pnpr/src/resolver/pypi.rs[379-390]
pnpr/crates/pnpr/src/resolver/pypi.rs[495-515]
pnpr/crates/pnpr/src/resolver/pypi.rs[194-207]
pnpr/crates/pnpr/src/resolver/pypi.rs[150-160]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
Cached metadata remains reusable after the index changes the digest associated with the same URL, bypassing the verification performed for fresh responses.

## Issue Context
Include the relevant core-metadata SHA-256 or fallback wheel SHA-256 in the cache identity, or persist and compare that identity before accepting a cache hit. Define safe behavior when the index supplies no supported digest.

## Fix Focus Areas
- pnpr/crates/pnpr/src/resolver/pypi.rs[276-305]
- pnpr/crates/pnpr/src/resolver/pypi.rs[379-390]
- pnpr/crates/pnpr/src/resolver/pypi.rs[495-515]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


4. Python projects get stale lockfiles ✓ Resolved 🐞 Bug ≡ Correctness
Description
prepare accepts a server lockfile when lock.tool.pnpm matches inputs, but it never compares
lock.requires_python with project.requires_python. A server response with a different top-level
constraint is written successfully, then the existing-lock freshness check rejects it on the next
install and frozen-lockfile installs fail.
Code

pnpm/crates/cli/src/python.rs[R228-230]

+                if lock.tool.pnpm != inputs {
+                    bail!("the pnpr server resolved Python dependencies for other inputs");
+                }
Relevance

●●● Strong

Accepted precedents consistently require lockfile freshness checks to validate all request inputs,
including mismatched settings.

PR-#13386
PR-#12144

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
The client sends the project constraint to the server, but only validates the nested resolver inputs
on return. The lockfile model stores the constraint separately, and the existing-lock path proves
that it is required for freshness.

pnpm/crates/cli/src/python.rs[213-234]
pnpm/crates/cli/src/python.rs[201-205]
pnpm/crates/python-resolver/src/lockfile.rs[20-27]
pnpm/crates/python-resolver/src/lockfile.rs[36-64]
pnpr/crates/pnpr/src/resolver/pypi.rs[127-137]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
Validate the returned lockfile's `requires_python` against the requesting project's `requires_python` before accepting and writing a pnpr-produced lockfile.

## Issue Context
`tool.pnpm` deliberately does not include the project-level Python constraint, while ordinary lock reuse compares that separate field. A mismatched server response currently writes a lock that is immediately considered stale on the next run.

## Fix Focus Areas
- pnpm/crates/cli/src/python.rs[222-234]
- pnpm/crates/cli/src/python.rs[201-205]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


5. Bad index responses poison the cache ✓ Resolved 🐞 Bug ☼ Reliability
Description
read_bytes stores every successful response before its caller parses the page, verifies the
published digest, or opens the wheel archive. A transient malformed page, mismatched metadata
document, or corrupt wheel is consequently replayed to every later resolve in the same cache scope
until the configured time-to-live expires.
Code

pnpr/crates/pnpr/src/resolver/pypi.rs[R325-327]

+        let body = self.hold(kind, response.body)?;
+        Self::store(cache_path, CachedDocument { url: source.to_string(), body: body.clone() })
+            .await;
Relevance

●●● Strong

Accepted cache precedents require invalid or unvalidated data to be removed or rejected rather than
repeatedly reused.

PR-#12144

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
Page parsing occurs after read, metadata digest checking occurs after read, and wheel digest and
ZIP validation occur after read_bytes, but read_bytes has already written the body at that
point. Fresh cache entries are accepted based only on age and JSON deserialization and are returned
without eviction, matching the previously accepted store-before-validation cache-poisoning pattern.

pnpr/crates/pnpr/src/resolver/pypi.rs[220-230]
pnpr/crates/pnpr/src/resolver/pypi.rs[244-258]
pnpr/crates/pnpr/src/resolver/pypi.rs[288-327]
pnpr/crates/pnpr/src/resolver/pypi.rs[368-376]
PR-#14598

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
The shared Python index cache persists upstream bodies before semantic parsing, digest verification, and wheel validation. Invalid transient responses therefore remain fresh cache hits and repeatedly fail subsequent clients.

## Issue Context
Move cache insertion after the relevant validation succeeds, introduce a validator-aware cache loader, or remove the just-written entry whenever downstream validation fails. Add regression coverage proving that a bad first response is not reused and a later corrected response is fetched.

## Fix Focus Areas
- pnpr/crates/pnpr/src/resolver/pypi.rs[220-230]
- pnpr/crates/pnpr/src/resolver/pypi.rs[244-258]
- pnpr/crates/pnpr/src/resolver/pypi.rs[288-327]
- pnpr/crates/pnpr/src/resolver/pypi.rs[368-386]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


View medium (2)
6. Users get implementation-heavy notes ✓ Resolved 📘 Rule violation ⚙ Maintainability
Description
The changeset's second sentence uses because to explain pnpr's internal metadata-reading mechanism
behind the download change. It appears in the sole user-facing entry, so generated release notes
include design justification alongside observable behavior.
Code

.changeset/python-resolution-through-pnpr.md[6]

+`pnpm install` now resolves Python dependencies through the server configured in `pnprServer`. The client no longer downloads a wheel to find out what it requires, because pnpr reads the metadata file the index publishes beside it. pnpm still downloads the wheels the returned lockfile names, checks them against the index's digests, and re-resolves the project against them. If the server does not serve Python resolution, pnpm resolves Python dependencies locally.
Relevance

●●● Strong

Recent changeset precedents explicitly accepted removing implementation rationale and keeping
observable user-facing behavior.

PR-#14547
PR-#14526
PR-#14157

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
PR Compliance ID 3058322 prohibits changeset entries from including justification clauses such as
because and requires them to describe observable behavior only. The added entry explains the
implementation reason for avoiding wheel downloads with because pnpr reads the metadata file,
directly matching the prohibited pattern.

Rule 3058322: Changeset entries must describe observable behavior changes only
.changeset/python-resolution-through-pnpr.md[6-6]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
Remove the design-justification clause from the changeset and retain only concrete, observable behavior.

## Issue Context
The sentence uses `because` to explain pnpr's internal metadata-fetching mechanism, which does not belong in user-facing release notes.

## Fix Focus Areas
- .changeset/python-resolution-through-pnpr.md[6-6]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


7. Query-based Python indexes fail ✓ Resolved 🐞 Bug ≡ Correctness
Description
IndexReader::candidates creates project-page addresses by joining name/ onto the configured
index URL, which removes the base URL's query component. An index that uses a query parameter for
routing or a signed request is contacted at a different address on the pnpr path, so resolution
fails even though the original configured index was valid.
Code

pnpr/crates/pnpr/src/resolver/pypi.rs[R215-218]

+        let page_url = self
+            .index
+            .join(&format!("{name}/"))
+            .map_err(|err| format!("build the index URL for {name}: {err}"))?;
Relevance

●● Moderate

URL construction correctness issue is specific and plausible, but historical searches found no
closely matching precedent.

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
index_url retains the parsed URL's query while normalizing only its path, but candidates
subsequently uses relative joining to construct the actual project request. That resulting page URL
is passed directly to read and becomes the base used for artifact links, with no code restoring
the original query.

pnpr/crates/pnpr/src/resolver/pypi.rs[202-229]
pnpr/crates/pnpr/src/resolver/pypi.rs[454-464]
pnpm/crates/cli/src/python.rs[142-158]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
Building a project-page URL with relative URL joining discards query parameters from the configured Python index. Query-routed and signed index endpoints are therefore changed before pnpr fetches them.

## Issue Context
Construct the project path while explicitly preserving the configured query, and add coverage for an index such as `https://registry.example/simple/?tenant=x`. Ensure relative artifact links still resolve against the final project-page response URL.

## Fix Focus Areas
- pnpr/crates/pnpr/src/resolver/pypi.rs[202-229]
- pnpr/crates/pnpr/src/resolver/pypi.rs[454-464]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


Grey Divider

Context sources
✅ Compliance rules (platform): 46 rules
Review mode: ⚖️ Balanced: This push changes runtime metadata-cache keying for unverified wheel-derived data, creating security and correctness implications, but the logic is localized enough for a single thorough review.

Grey Divider

Tip of the day
💡 Did you know, you can show, collapse, or hide each part of a finding: code, evidence, and all

More tips ↗ | Customize Qodo ↗ | Qodo docs ↗

Grey Divider

Previous reviews

Review updated until commit 221a53e

Results up to commit 4933980 🧠 Deep


🐞 Bugs (0) 📘 Rule violations (0) 📎 Requirement gaps (0) 🎨 UX issues (0) 🔗 Cross-repo conflicts (0) 📜 Skill insights (0)


Action required
1. Large wheels exhaust server resources ✓ Resolved 🐞 Bug ➹ Performance
Description
read_bytes clones every fetched body into CachedDocument, whose ordinary Vec<u8> is then
serialized by serde_json as a decimal-number array. A permitted 256-MiB fallback wheel can
therefore coexist with two binary copies and roughly 0.5–1.1 GiB of JSON while also producing an
exceptionally large cache write.
Code

pnpr/crates/pnpr/src/resolver/pypi.rs[R325-327]

+        let body = self.hold(kind, response.body)?;
+        Self::store(cache_path, CachedDocument { url: source.to_string(), body: body.clone() })
+            .await;
Relevance

●● Moderate

Large-response memory amplification is plausible, but no close precedent establishes team treatment
of this performance concern.

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
Fallback wheels may be 256 MiB, and the response body is cloned before cache serialization.
CachedDocument derives normal Serde behavior over Vec<u8>, while serde_json::to_vec creates a
separate JSON numeric-array buffer before the atomic write; unlike this path, the analogous Cargo
cache writes already-serialized text directly.

pnpr/crates/pnpr/src/resolver/pypi.rs[70-72]
pnpr/crates/pnpr/src/resolver/pypi.rs[323-328]
pnpr/crates/pnpr/src/resolver/pypi.rs[378-386]
pnpr/crates/pnpr/src/resolver/pypi.rs[391-397]
pnpr/crates/pnpr/src/resolver/cargo.rs[350-360]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
Fallback wheel bodies are cloned and serialized as JSON arrays of byte values, causing severe memory and disk amplification for large valid wheels. The 256-MiB wheel limit makes peak allocations and cache files large enough to threaten server availability.

## Issue Context
Use a compact binary cache representation, stream the cache write where possible, or avoid caching whole fallback wheels after extracting their metadata. Preserve the final redirected source URL without wrapping raw wheel bytes in ordinary JSON serialization.

## Fix Focus Areas
- pnpr/crates/pnpr/src/resolver/pypi.rs[70-72]
- pnpr/crates/pnpr/src/resolver/pypi.rs[323-328]
- pnpr/crates/pnpr/src/resolver/pypi.rs[378-386]
- pnpr/crates/pnpr/src/resolver/pypi.rs[391-397]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


2. Crafted targets can stall the server ✓ Resolved 🐞 Bug ⛨ Security
Description
PypiResolveRequest accepts an unconstrained target tag list, and candidates_from_page compares
every advertised wheel against that entire caller-supplied list. An authenticated caller can combine
many tags with a large Simple API page to force multiplicative parsing and string allocation before
the distribution or metadata-read limits apply.
Code

pnpm/crates/python-resolver/src/candidates.rs[75]

+        let Some((wheel_name, version, rank)) = wheel_identity(&file.filename, &target.tags)?
Relevance

●● Moderate

Security resource-exhaustion concern is plausible, but no closely matching accepted or rejected
precedent was found.

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
The request schema places no bounds on target, whose tags are supplied by the remote caller. Each
file in the up-to-32-MiB project page calls wheel_identity, and that function linearly scans and
splits every supplied tag until it finds a match, yielding work proportional to files multiplied by
tags; the resolve route otherwise inherits the broad 100-MiB server body limit.

pnpr/crates/pnpr/src/resolver/protocol.rs[56-69]
pnpr/crates/pnpr/src/resolver/pypi.rs[54-77]
pnpm/crates/python-resolver/src/candidates.rs[71-76]
pnpm/crates/python-resolver/src/candidates.rs[110-122]
pnpr/crates/pnpr/src/server/routing.rs[137-145]
pnpr/crates/pnpr/src/server/routing.rs[204-211]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
PyPI resolve requests permit an unbounded target tag list, while every index wheel scans that list and repeatedly splits tag strings. This permits an authenticated caller to create multiplicative CPU and allocation work from one request.

## Issue Context
The existing distribution, metadata-read, and upstream-byte limits do not constrain request fields or the number of tag comparisons performed per page. Add defensible request/tag limits and pre-parse the target tags into a representation that avoids repeated splitting for every wheel.

## Fix Focus Areas
- pnpr/crates/pnpr/src/resolver/protocol.rs[56-69]
- pnpr/crates/pnpr/src/resolver/pypi.rs[87-110]
- pnpm/crates/python-resolver/src/candidates.rs[71-76]
- pnpm/crates/python-resolver/src/candidates.rs[110-122]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools



Remediation recommended
3. Users get implementation-heavy notes ✓ Resolved 📘 Rule violation ⚙ Maintainability
Description
The changeset's second sentence uses because to explain pnpr's internal metadata-reading mechanism
behind the download change. It appears in the sole user-facing entry, so generated release notes
include design justification alongside observable behavior.
Code

.changeset/python-resolution-through-pnpr.md[6]

+`pnpm install` now resolves Python dependencies through the server configured in `pnprServer`. The client no longer downloads a wheel to find out what it requires, because pnpr reads the metadata file the index publishes beside it. pnpm still downloads the wheels the returned lockfile names, checks them against the index's digests, and re-resolves the project against them. If the server does not serve Python resolution, pnpm resolves Python dependencies locally.
Relevance

●●● Strong

Recent changeset precedents explicitly accepted removing implementation rationale and keeping
observable user-facing behavior.

PR-#14547
PR-#14526
PR-#14157

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
PR Compliance ID 3058322 prohibits changeset entries from including justification clauses such as
because and requires them to describe observable behavior only. The added entry explains the
implementation reason for avoiding wheel downloads with because pnpr reads the metadata file,
directly matching the prohibited pattern.

Rule 3058322: Changeset entries must describe observable behavior changes only
.changeset/python-resolution-through-pnpr.md[6-6]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
Remove the design-justification clause from the changeset and retain only concrete, observable behavior.

## Issue Context
The sentence uses `because` to explain pnpr's internal metadata-fetching mechanism, which does not belong in user-facing release notes.

## Fix Focus Areas
- .changeset/python-resolution-through-pnpr.md[6-6]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


4. Python projects get stale lockfiles ✓ Resolved 🐞 Bug ≡ Correctness
Description
prepare accepts a server lockfile when lock.tool.pnpm matches inputs, but it never compares
lock.requires_python with project.requires_python. A server response with a different top-level
constraint is written successfully, then the existing-lock freshness check rejects it on the next
install and frozen-lockfile installs fail.
Code

pnpm/crates/cli/src/python.rs[R228-230]

+                if lock.tool.pnpm != inputs {
+                    bail!("the pnpr server resolved Python dependencies for other inputs");
+                }
Relevance

●●● Strong

Accepted precedents consistently require lockfile freshness checks to validate all request inputs,
including mismatched settings.

PR-#13386
PR-#12144

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
The client sends the project constraint to the server, but only validates the nested resolver inputs
on return. The lockfile model stores the constraint separately, and the existing-lock path proves
that it is required for freshness.

pnpm/crates/cli/src/python.rs[213-234]
pnpm/crates/cli/src/python.rs[201-205]
pnpm/crates/python-resolver/src/lockfile.rs[20-27]
pnpm/crates/python-resolver/src/lockfile.rs[36-64]
pnpr/crates/pnpr/src/resolver/pypi.rs[127-137]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
Validate the returned lockfile's `requires_python` against the requesting project's `requires_python` before accepting and writing a pnpr-produced lockfile.

## Issue Context
`tool.pnpm` deliberately does not include the project-level Python constraint, while ordinary lock reuse compares that separate field. A mismatched server response currently writes a lock that is immediately considered stale on the next run.

## Fix Focus Areas
- pnpm/crates/cli/src/python.rs[222-234]
- pnpm/crates/cli/src/python.rs[201-205]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


5. Bad index responses poison the cache ✓ Resolved 🐞 Bug ☼ Reliability
Description
read_bytes stores every successful response before its caller parses the page, verifies the
published digest, or opens the wheel archive. A transient malformed page, mismatched metadata
document, or corrupt wheel is consequently replayed to every later resolve in the same cache scope
until the configured time-to-live expires.
Code

pnpr/crates/pnpr/src/resolver/pypi.rs[R325-327]

+        let body = self.hold(kind, response.body)?;
+        Self::store(cache_path, CachedDocument { url: source.to_string(), body: body.clone() })
+            .await;
Relevance

●●● Strong

Accepted cache precedents require invalid or unvalidated data to be removed or rejected rather than
repeatedly reused.

PR-#12144

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
Page parsing occurs after read, metadata digest checking occurs after read, and wheel digest and
ZIP validation occur after read_bytes, but read_bytes has already written the body at that
point. Fresh cache entries are accepted based only on age and JSON deserialization and are returned
without eviction, matching the previously accepted store-before-validation cache-poisoning pattern.

pnpr/crates/pnpr/src/resolver/pypi.rs[220-230]
pnpr/crates/pnpr/src/resolver/pypi.rs[244-258]
pnpr/crates/pnpr/src/resolver/pypi.rs[288-327]
pnpr/crates/pnpr/src/resolver/pypi.rs[368-376]
PR-#14598

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
The shared Python index cache persists upstream bodies before semantic parsing, digest verification, and wheel validation. Invalid transient responses therefore remain fresh cache hits and repeatedly fail subsequent clients.

## Issue Context
Move cache insertion after the relevant validation succeeds, introduce a validator-aware cache loader, or remove the just-written entry whenever downstream validation fails. Add regression coverage proving that a bad first response is not reused and a later corrected response is fetched.

## Fix Focus Areas
- pnpr/crates/pnpr/src/resolver/pypi.rs[220-230]
- pnpr/crates/pnpr/src/resolver/pypi.rs[244-258]
- pnpr/crates/pnpr/src/resolver/pypi.rs[288-327]
- pnpr/crates/pnpr/src/resolver/pypi.rs[368-386]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


View medium (1)
6. Query-based Python indexes fail ✓ Resolved 🐞 Bug ≡ Correctness
Description
IndexReader::candidates creates project-page addresses by joining name/ onto the configured
index URL, which removes the base URL's query component. An index that uses a query parameter for
routing or a signed request is contacted at a different address on the pnpr path, so resolution
fails even though the original configured index was valid.
Code

pnpr/crates/pnpr/src/resolver/pypi.rs[R215-218]

+        let page_url = self
+            .index
+            .join(&format!("{name}/"))
+            .map_err(|err| format!("build the index URL for {name}: {err}"))?;
Relevance

●● Moderate

URL construction correctness issue is specific and plausible, but historical searches found no
closely matching precedent.

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
index_url retains the parsed URL's query while normalizing only its path, but candidates
subsequently uses relative joining to construct the actual project request. That resulting page URL
is passed directly to read and becomes the base used for artifact links, with no code restoring
the original query.

pnpr/crates/pnpr/src/resolver/pypi.rs[202-229]
pnpr/crates/pnpr/src/resolver/pypi.rs[454-464]
pnpm/crates/cli/src/python.rs[142-158]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
Building a project-page URL with relative URL joining discards query parameters from the configured Python index. Query-routed and signed index endpoints are therefore changed before pnpr fetches them.

## Issue Context
Construct the project path while explicitly preserving the configured query, and add coverage for an index such as `https://registry.example/simple/?tenant=x`. Ensure relative artifact links still resolve against the final project-page response URL.

## Fix Focus Areas
- pnpr/crates/pnpr/src/resolver/pypi.rs[202-229]
- pnpr/crates/pnpr/src/resolver/pypi.rs[454-464]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


Grey Divider

Qodo Logo

Comment thread pnpr/crates/pnpr/src/resolver/pypi.rs Resolved
@qodo-code-review

qodo-code-review Bot commented Sep 6, 2026 •

Copy link
Copy Markdown

PR Code Suggestions ✨

Latest suggestions up to 221a53e

Warning

/improve is deprecated. Use /agentic_review instead (removal date not yet scheduled).

CategorySuggestion                                                                                                                                    Impact
Security
Validate redirects before fetching

Validate HTTP redirect targets against the route policy to prevent SSRF
vulnerabilities.

pnpr/crates/pnpr/src/resolver/pypi.rs [356-374]

 let response = self
     .client
-    .get_limited_bytes_with_secure_auth_and_retry(
+    .get_limited_bytes_with_secure_auth_and_retry_and_redirect_check(
         url.as_str(),
         auth,
         accept,
         RetryOpts::default(),
         limit,
+        |redirect| auth.allows_fetch(redirect.as_str()),
     )
     .await
     .map_err(|err| format!("fetch the {kind} at {url}: {err}"))?;
 ...
 let source = url::Url::parse(&response.url)
     .map_err(|err| format!("parse the URL the {kind} was read from: {err}"))?;

[To ensure code accuracy, apply this suggestion manually]

Suggestion importance[1-10]: 7

__

Why: The suggestion correctly identifies a potential Server-Side Request Forgery (SSRF) risk via HTTP redirects, although it proposes using a likely hallucinated method name (get_limited_bytes_with_secure_auth_and_retry_and_redirect_check) for the external pnpm_network crate.

Medium
Restrict server-provided artifact URLs

Validate server-provided wheel URLs against an outbound-fetch policy to prevent
SSRF vulnerabilities.

pnpm/crates/cli/src/python.rs [222-224]

 accept_server_lockfile(&lock, &inputs, project.requires_python.as_deref())?;
+validate_server_wheel_urls(config, &lock)?;
 lock.seed(&mut registry.packages)?;
 registry.fetch_wheels::<Reporter>(&lock.packages).await?;

[To ensure code accuracy, apply this suggestion manually]

Suggestion importance[1-10]: 4

__

Why: While mitigating potential SSRF from a compromised server is a valid security concept, the suggestion assumes a non-existent outbound-fetch policy in the client configuration and proposes an undefined function validate_server_wheel_urls.

Low
Possible issue
Bind cached metadata to artifacts

Avoid caching wheel metadata when no hash is available to prevent reusing stale
data if the artifact is silently republished at the same URL.

pnpr/crates/pnpr/src/resolver/pypi.rs [285-313]

 let derived_from = match candidate.core_metadata {
     Some(_) => None,
     None => candidate.wheel.hashes.get("sha256").map(String::as_str),
 };
-let cache_path = self.cache_path(&auth, &metadata_url(&wheel_url), derived_from);
-if let Some(cached) = self.cached(&cache_path).await {
-    let document = self.hold("metadata", cached.body)?;
-    return Self::cached_metadata(&document, name, version, candidate);
+let cache_path = if candidate.core_metadata.is_some() || derived_from.is_some() {
+    Some(self.cache_path(&auth, &metadata_url(&wheel_url), derived_from))
+} else {
+    None
+};
+if let Some(cache_path) = &cache_path {
+    if let Some(cached) = self.cached(cache_path).await {
+        let document = self.hold("metadata", cached.body)?;
+        return Self::cached_metadata(&document, name, version, candidate);
+    }
 }
 ...
-Self::store(cache_path, CachedDocument { url: wheel_url.to_string(), body: document })
+if let Some(cache_path) = cache_path {
+    Self::store(
+        cache_path,
+        CachedDocument { url: wheel_url.to_string(), body: document.clone() },
+    )
     .await;
+}

[To ensure code accuracy, apply this suggestion manually]

Suggestion importance[1-10]: 4

__

Why: Caching by URL without a hash is a reasonable fallback when an index omits hashes, so skipping the cache entirely for this edge case might unnecessarily impact performance for a rare scenario.

Low
  • Update

Previous suggestions

✅ Suggestions up to commit ee1f583
CategorySuggestion                                                                                                                                    Impact
Possible issue
✅ Key cached metadata by digest
Suggestion Impact:The commit extends cache_path with an optional artifact digest and uses the wheel's SHA-256 digest for fallback metadata lacking published core metadata, thereby invalidating cached extracted metadata when the wheel changes.

code diff:

@@ -278,7 +278,15 @@
             .map_err(|err| format!("parse the wheel URL for {name}: {err}"))?;
         validate_url(&wheel_url).map_err(|err| super::report_message(&err))?;
         let auth = self.auth_for(&canonical_name);
-        let cache_path = self.cache_path(&auth, &metadata_url(&wheel_url));
+        // An index that publishes a metadata file vouches for a digest
+        // `cached_metadata` re-checks. One that publishes none leaves the
+        // extracted document nothing to be checked against, so its cache
+        // entry is bound to the wheel it came out of instead.
+        let derived_from = match candidate.core_metadata {
+            Some(_) => None,
+            None => candidate.wheel.hashes.get("sha256").map(String::as_str),
+        };
+        let cache_path = self.cache_path(&auth, &metadata_url(&wheel_url), derived_from);
         if let Some(cached) = self.cached(&cache_path).await {
             let document = self.hold("metadata", cached.body)?;
             return Self::cached_metadata(&document, name, version, candidate);
@@ -395,14 +403,25 @@
     /// Where `url`'s document is cached. The route scope keys the
     /// namespace, so a private index cached under one caller's credential
     /// is never read back for a caller who does not reproduce that scope.
-    fn cache_path(&self, auth: &AuthHeaders, url: &url::Url) -> PathBuf {
+    /// Where the document read from `url` is cached. `derived_from` is the
+    /// digest of the artifact a document was extracted from rather than
+    /// read whole, and joins the key so a republished artifact is read
+    /// again rather than answered from what came out of the old one.
+    fn cache_path(
+        &self,
+        auth: &AuthHeaders,
+        url: &url::Url,
+        derived_from: Option<&str>,
+    ) -> PathBuf {
         let scope = match auth.metadata_scope(url.as_str(), None) {
             MetadataCacheScope::Public => "public".to_string(),
             MetadataCacheScope::Private { descriptor_id } => descriptor_id,
         };
-        self.cache_dir
-            .join(scope)
-            .join(format!("{}.json", pnpm_crypto_hash::create_hex_hash(url.as_str())))
+        let key = match derived_from {
+            Some(digest) => format!("{url}#{digest}"),
+            None => url.to_string(),
+        };
+        self.cache_dir.join(scope).join(format!("{}.json", pnpm_crypto_hash::create_hex_hash(&key)))

Add the metadata or wheel digest to the cache key to prevent reusing stale
fallback metadata when a wheel is updated.

pnpr/crates/pnpr/src/resolver/pypi.rs [280-281]

 let auth = self.auth_for(&canonical_name);
-let cache_path = self.cache_path(&auth, &metadata_url(&wheel_url));
+let metadata_url = metadata_url(&wheel_url);
+let cache_digests =
+    candidate.core_metadata.as_ref().unwrap_or(&candidate.wheel.hashes);
+let cache_path = self.cache_path_with_digests(
+    &auth,
+    &metadata_url,
+    cache_digests,
+);
Suggestion importance[1-10]: 9

__

Why: It correctly identifies a bug where cached fallback metadata isn't invalidated or checked against the new wheel hash when the wheel changes, leading to stale metadata being accepted.

High
Security
Validate server-provided artifact URLs

Validate artifact URLs loaded from server-provided lockfiles to prevent fetching
unauthorized or local paths. Ensure that URLs from pnpr server responses adhere
to the same security constraints as those parsed from an index.

pnpm/crates/python-resolver/src/lockfile.rs [148-152]

 for package in &self.packages {
     let [wheel] = package.wheels.as_slice() else {
         bail!("pnpm requires one target-compatible wheel per locked Python package")
     };
+    let url: url::Url = wheel.url.parse().into_diagnostic()?;
+    crate::candidates::validate_url(&url)?;
     wheel.integrity()?;
Suggestion importance[1-10]: 9

__

Why: The suggestion addresses a critical security vulnerability where a compromised pnpr server could supply malicious URLs (e.g., file://) that would be fetched during installation, bypassing the validate_url check.

High
Reject credential-bearing artifact URLs

Check and reject wheel_url if it contains inline credentials to prevent
credential leaking or bypassing alias policies.

pnpr/crates/pnpr/src/resolver/pypi.rs [277-279]

 let wheel_url = url::Url::parse(&candidate.wheel.url)
     .map_err(|err| format!("parse the wheel URL for {name}: {err}"))?;
 validate_url(&wheel_url).map_err(|err| super::report_message(&err))?;
+if url_has_inline_credentials(wheel_url.as_str()) {
+    return Err(format!(
+        "inline URL credentials are not allowed in the wheel URL for {name}",
+    ));
+}
Suggestion importance[1-10]: 8

__

Why: This is an excellent security catch that prevents credentials from being silently fetched, cached, and leaked into the pylock.toml file via a malicious or misconfigured index.

Medium
Suggestions up to commit 3013392
CategorySuggestion                                                                                                                                    Impact
Possible issue
✅ Key cached metadata by digest
Suggestion Impact:The commit extends cache_path with an optional artifact digest and uses the wheel's SHA-256 digest for fallback metadata lacking published core metadata, thereby invalidating cached extracted metadata when the wheel changes.

code diff:

@@ -278,7 +278,15 @@
             .map_err(|err| format!("parse the wheel URL for {name}: {err}"))?;
         validate_url(&wheel_url).map_err(|err| super::report_message(&err))?;
         let auth = self.auth_for(&canonical_name);
-        let cache_path = self.cache_path(&auth, &metadata_url(&wheel_url));
+        // An index that publishes a metadata file vouches for a digest
+        // `cached_metadata` re-checks. One that publishes none leaves the
+        // extracted document nothing to be checked against, so its cache
+        // entry is bound to the wheel it came out of instead.
+        let derived_from = match candidate.core_metadata {
+            Some(_) => None,
+            None => candidate.wheel.hashes.get("sha256").map(String::as_str),
+        };
+        let cache_path = self.cache_path(&auth, &metadata_url(&wheel_url), derived_from);
         if let Some(cached) = self.cached(&cache_path).await {
             let document = self.hold("metadata", cached.body)?;
             return Self::cached_metadata(&document, name, version, candidate);
@@ -395,14 +403,25 @@
     /// Where `url`'s document is cached. The route scope keys the
     /// namespace, so a private index cached under one caller's credential
     /// is never read back for a caller who does not reproduce that scope.
-    fn cache_path(&self, auth: &AuthHeaders, url: &url::Url) -> PathBuf {
+    /// Where the document read from `url` is cached. `derived_from` is the
+    /// digest of the artifact a document was extracted from rather than
+    /// read whole, and joins the key so a republished artifact is read
+    /// again rather than answered from what came out of the old one.
+    fn cache_path(
+        &self,
+        auth: &AuthHeaders,
+        url: &url::Url,
+        derived_from: Option<&str>,
+    ) -> PathBuf {
         let scope = match auth.metadata_scope(url.as_str(), None) {
             MetadataCacheScope::Public => "public".to_string(),
             MetadataCacheScope::Private { descriptor_id } => descriptor_id,
         };
-        self.cache_dir
-            .join(scope)
-            .join(format!("{}.json", pnpm_crypto_hash::create_hex_hash(url.as_str())))
+        let key = match derived_from {
+            Some(digest) => format!("{url}#{digest}"),
+            None => url.to_string(),
+        };
+        self.cache_dir.join(scope).join(format!("{}.json", pnpm_crypto_hash::create_hex_hash(&key)))

Add the metadata or wheel digest to the cache key to prevent reusing stale
fallback metadata when a wheel is updated.

pnpr/crates/pnpr/src/resolver/pypi.rs [280-281]

 let auth = self.auth_for(&canonical_name);
-let cache_path = self.cache_path(&auth, &metadata_url(&wheel_url));
+let metadata_url = metadata_url(&wheel_url);
+let cache_digests =
+    candidate.core_metadata.as_ref().unwrap_or(&candidate.wheel.hashes);
+let cache_path = self.cache_path_with_digests(
+    &auth,
+    &metadata_url,
+    cache_digests,
+);
Suggestion importance[1-10]: 9

__

Why: It correctly identifies a bug where cached fallback metadata isn't invalidated or checked against the new wheel hash when the wheel changes, leading to stale metadata being accepted.

High
Security
Reject credential-bearing artifact URLs

Check and reject wheel_url if it contains inline credentials to prevent
credential leaking or bypassing alias policies.

pnpr/crates/pnpr/src/resolver/pypi.rs [277-279]

 let wheel_url = url::Url::parse(&candidate.wheel.url)
     .map_err(|err| format!("parse the wheel URL for {name}: {err}"))?;
 validate_url(&wheel_url).map_err(|err| super::report_message(&err))?;
+if url_has_inline_credentials(wheel_url.as_str()) {
+    return Err(format!(
+        "inline URL credentials are not allowed in the wheel URL for {name}",
+    ));
+}
Suggestion importance[1-10]: 8

__

Why: This is an excellent security catch that prevents credentials from being silently fetched, cached, and leaked into the pylock.toml file via a malicious or misconfigured index.

Medium
✅ Suggestions up to commit 4833b6d
CategorySuggestion                                                                                                                                    Impact
Possible issue
✅ Key metadata cache by digest
Suggestion Impact:The commit adds the wheel SHA-256 digest to the cache key when metadata is extracted from a wheel, causing cache invalidation when that wheel is republished. It differs from the proposed implementation by retaining URL-only keys for separately advertised metadata and by using a single optional digest rather than source type plus full digest maps.

code diff:

@@ -278,7 +278,15 @@
             .map_err(|err| format!("parse the wheel URL for {name}: {err}"))?;
         validate_url(&wheel_url).map_err(|err| super::report_message(&err))?;
         let auth = self.auth_for(&canonical_name);
-        let cache_path = self.cache_path(&auth, &metadata_url(&wheel_url));
+        // An index that publishes a metadata file vouches for a digest
+        // `cached_metadata` re-checks. One that publishes none leaves the
+        // extracted document nothing to be checked against, so its cache
+        // entry is bound to the wheel it came out of instead.
+        let derived_from = match candidate.core_metadata {
+            Some(_) => None,
+            None => candidate.wheel.hashes.get("sha256").map(String::as_str),
+        };
+        let cache_path = self.cache_path(&auth, &metadata_url(&wheel_url), derived_from);
         if let Some(cached) = self.cached(&cache_path).await {
             let document = self.hold("metadata", cached.body)?;
             return Self::cached_metadata(&document, name, version, candidate);
@@ -395,14 +403,25 @@
     /// Where `url`'s document is cached. The route scope keys the
     /// namespace, so a private index cached under one caller's credential
     /// is never read back for a caller who does not reproduce that scope.
-    fn cache_path(&self, auth: &AuthHeaders, url: &url::Url) -> PathBuf {
+    /// Where the document read from `url` is cached. `derived_from` is the
+    /// digest of the artifact a document was extracted from rather than
+    /// read whole, and joins the key so a republished artifact is read
+    /// again rather than answered from what came out of the old one.
+    fn cache_path(
+        &self,
+        auth: &AuthHeaders,
+        url: &url::Url,
+        derived_from: Option<&str>,
+    ) -> PathBuf {
         let scope = match auth.metadata_scope(url.as_str(), None) {
             MetadataCacheScope::Public => "public".to_string(),
             MetadataCacheScope::Private { descriptor_id } => descriptor_id,
         };
-        self.cache_dir
-            .join(scope)
-            .join(format!("{}.json", pnpm_crypto_hash::create_hex_hash(url.as_str())))
+        let key = match derived_from {
+            Some(digest) => format!("{url}#{digest}"),
+            None => url.to_string(),
+        };
+        self.cache_dir.join(scope).join(format!("{}.json", pnpm_crypto_hash::create_hex_hash(&key)))

Incorporate the advertised digest and metadata source type into the metadata
cache key to ensure cache invalidation upon wheel republication.

pnpr/crates/pnpr/src/resolver/pypi.rs [281]

-        let cache_path = self.cache_path(&auth, &metadata_url(&wheel_url));
+        let metadata_location = metadata_url(&wheel_url);
+        let cache_path = match &candidate.core_metadata {
+            Some(digests) => {
+                self.content_cache_path(&auth, &metadata_location, "metadata", digests)
+            }
+            None => self.content_cache_path(
+                &auth,
+                &metadata_location,
+                "wheel",
+                &candidate.wheel.hashes,
+            ),
+        };
 
+    fn content_cache_path(
+        &self,
+        auth: &AuthHeaders,
+        url: &url::Url,
+        source: &str,
+        digests: &BTreeMap<String, String>,
+    ) -> PathBuf {
+        let scope = match auth.metadata_scope(url.as_str(), None) {
+            MetadataCacheScope::Public => "public".to_string(),
+            MetadataCacheScope::Private { descriptor_id } => descriptor_id,
+        };
+        let identity = format!("{source}:{url}:{digests:?}");
+        self.cache_dir
+            .join(scope)
+            .join(format!("{}.json", pnpm_crypto_hash::create_hex_hash(&identity)))
+    }
+
Suggestion importance[1-10]: 9

__

Why: Including the wheel's digest in the cache key prevents the reuse of stale metadata if a wheel is republished under the same URL, which is critical since the extracted metadata cannot be directly verified against the wheel's overall hash.

High
Security
Validate locked artifact URLs

Add URL validation for locked wheels during lockfile seeding.

pnpm/crates/python-resolver/src/lockfile.rs [152]

+let url: url::Url = wheel.url.parse().into_diagnostic()?;
+crate::validate_url(&url)?;
 wheel.integrity()?;
Suggestion importance[1-10]: 9

__

Why: Validating the URL of each locked artifact is a critical security measure to prevent a compromised server or tampered lockfile from causing the client to fetch non-HTTP schemes or credential-bearing URLs.

High
✅ Suggestions up to commit 4b5c674
CategorySuggestion                                                                                                                                    Impact
Security
Validate remote artifact URLs

Add URL validation for wheels within server-provided lockfiles.

pnpm/crates/cli/src/python.rs [326-335]

 fn accept_server_lockfile(
     lock: &Lockfile,
     inputs: &Inputs,
     requires_python: Option<&str>,
 ) -> Result<()> {
     if lock.tool.pnpm != *inputs || lock.requires_python.as_deref() != requires_python {
         bail!("the pnpr server resolved Python dependencies for other inputs");
     }
+    for package in &lock.packages {
+        for wheel in &package.wheels {
+            let url = url::Url::parse(&wheel.url).into_diagnostic()?;
+            pnpm_python_resolver::validate_url(&url)?;
+        }
+    }
     Ok(())
 }
Suggestion importance[1-10]: 9

__

Why: The suggestion correctly identifies a security vulnerability where unverified URLs from a remote server might be fetched without validation, which could result in SSRF or unauthorized file reads.

High
Possible issue
✅ Bind cached metadata to digests
Suggestion Impact:The commit binds metadata extracted when core_metadata is absent to the wheel's SHA-256 digest by adding an optional derived_from component to the cache key. Unlike the suggestion, it does not include all digests or core_metadata digests.

code diff:

-        let cache_path = self.cache_path(&auth, &metadata_url(&wheel_url));
+        // An index that publishes a metadata file vouches for a digest
+        // `cached_metadata` re-checks. One that publishes none leaves the
+        // extracted document nothing to be checked against, so its cache
+        // entry is bound to the wheel it came out of instead.
+        let derived_from = match candidate.core_metadata {
+            Some(_) => None,
+            None => candidate.wheel.hashes.get("sha256").map(String::as_str),
+        };
+        let cache_path = self.cache_path(&auth, &metadata_url(&wheel_url), derived_from);
         if let Some(cached) = self.cached(&cache_path).await {
             let document = self.hold("metadata", cached.body)?;
             return Self::cached_metadata(&document, name, version, candidate);
@@ -395,14 +403,25 @@
     /// Where `url`'s document is cached. The route scope keys the
     /// namespace, so a private index cached under one caller's credential
     /// is never read back for a caller who does not reproduce that scope.
-    fn cache_path(&self, auth: &AuthHeaders, url: &url::Url) -> PathBuf {
+    /// Where the document read from `url` is cached. `derived_from` is the
+    /// digest of the artifact a document was extracted from rather than
+    /// read whole, and joins the key so a republished artifact is read
+    /// again rather than answered from what came out of the old one.
+    fn cache_path(
+        &self,
+        auth: &AuthHeaders,
+        url: &url::Url,
+        derived_from: Option<&str>,
+    ) -> PathBuf {
         let scope = match auth.metadata_scope(url.as_str(), None) {
             MetadataCacheScope::Public => "public".to_string(),
             MetadataCacheScope::Private { descriptor_id } => descriptor_id,
         };
-        self.cache_dir
-            .join(scope)
-            .join(format!("{}.json", pnpm_crypto_hash::create_hex_hash(url.as_str())))
+        let key = match derived_from {
+            Some(digest) => format!("{url}#{digest}"),
+            None => url.to_string(),
+        };
+        self.cache_dir.join(scope).join(format!("{}.json", pnpm_crypto_hash::create_hex_hash(&key)))

Modify the metadata cache key to include the advertised digests alongside the
URL. This prevents reusing stale, unverified metadata when core_metadata is
absent.

pnpr/crates/pnpr/src/resolver/pypi.rs [281]

-        let cache_path = self.cache_path(&auth, &metadata_url(&wheel_url));
+        let cache_path = self.metadata_cache_path(&auth, &wheel_url, candidate);
 
+    fn metadata_cache_path(
+        &self,
+        auth: &AuthHeaders,
+        wheel_url: &url::Url,
+        candidate: &Candidate,
+    ) -> PathBuf {
+        let mut identity = metadata_url(wheel_url).to_string();
+        match &candidate.core_metadata {
+            Some(digests) => {
+                identity.push_str("|metadata");
+                for (algorithm, digest) in digests {
+                    identity.push('|');
+                    identity.push_str(algorithm);
+                    identity.push('=');
+                    identity.push_str(digest);
+                }
+            }
+            None => {
+                identity.push_str("|wheel");
+                for (algorithm, digest) in &candidate.wheel.hashes {
+                    identity.push('|');
+                    identity.push_str(algorithm);
+                    identity.push('=');
+                    identity.push_str(digest);
+                }
+            }
+        }
+
+        let scope = match auth.metadata_scope(wheel_url.as_str(), None) {
+            MetadataCacheScope::Public => "public".to_string(),
+            MetadataCacheScope::Private { descriptor_id } => descriptor_id,
+        };
+        self.cache_dir
+            .join(scope)
+            .join(format!("{}.json", pnpm_crypto_hash::create_hex_hash(&identity)))
+    }
+
Suggestion importance[1-10]: 8

__

Why: Including the advertised digests in the metadata cache key prevents the silent reuse of stale cache entries when an index drops core_metadata or modifies wheel hashes without updating the URL.

Medium
✅ Suggestions up to commit e94bc5c
CategorySuggestion                                                                                                                                    Impact
Security
Reject credential-bearing wheel URLs

Add a validation check to reject wheel URLs that contain inline credentials.

pnpr/crates/pnpr/src/resolver/pypi.rs [277-279]

 let wheel_url = url::Url::parse(&candidate.wheel.url)
     .map_err(|err| format!("parse the wheel URL for {name}: {err}"))?;
 validate_url(&wheel_url).map_err(|err| super::report_message(&err))?;
+if url_has_inline_credentials(wheel_url.as_str()) {
+    return Err(format!(
+        "the wheel URL for {name} contains inline credentials, which are not allowed",
+    ));
+}
Suggestion importance[1-10]: 9

__

Why: Provides a valuable security enhancement to prevent potential credential leakage via malicious wheel URLs, correctly utilizing the already imported url_has_inline_credentials function.

High
✅ Bind cached metadata to integrity
Suggestion Impact:The commit extended cache_path with an optional source digest and uses the wheel SHA-256 in the metadata cache key when metadata is extracted from a wheel. It also verifies cached standalone metadata against the current index-provided digest, addressing the same integrity issue with a more nuanced implementation.

code diff:

-        let cache_path = self.cache_path(&auth, &page_url);
+        let cache_path = self.cache_path(&auth, &page_url, None);
         if let Some(cached) = self.cached(&cache_path).await {
             let source = cached.url(&page_url)?;
             let page = self.hold("page", cached.body)?;
@@ -278,15 +278,23 @@
             .map_err(|err| format!("parse the wheel URL for {name}: {err}"))?;
         validate_url(&wheel_url).map_err(|err| super::report_message(&err))?;
         let auth = self.auth_for(&canonical_name);
-        let cache_path = self.cache_path(&auth, &metadata_url(&wheel_url));
+        // An index that publishes a metadata file vouches for a digest
+        // `cached_metadata` re-checks. One that publishes none leaves the
+        // extracted document nothing to be checked against, so its cache
+        // entry is bound to the wheel it came out of instead.
+        let derived_from = match candidate.core_metadata {
+            Some(_) => None,
+            None => candidate.wheel.hashes.get("sha256").map(String::as_str),
+        };
+        let cache_path = self.cache_path(&auth, &metadata_url(&wheel_url), derived_from);
         if let Some(cached) = self.cached(&cache_path).await {
             let document = self.hold("metadata", cached.body)?;
-            return parse_metadata(&document, name, version, &candidate.wheel.name);
+            return Self::cached_metadata(&document, name, version, candidate);
         }
         let _reading = self.locks.lock(&cache_path.to_string_lossy()).await;
         if let Some(cached) = self.cached(&cache_path).await {
             let document = self.hold("metadata", cached.body)?;
-            return parse_metadata(&document, name, version, &candidate.wheel.name);
+            return Self::cached_metadata(&document, name, version, candidate);
         }
         let document = if let Some(digests) = &candidate.core_metadata {
             let (document, _) = self
@@ -306,6 +314,22 @@
         Ok(metadata)
     }
 
+    /// A cached metadata document, checked against what the index says
+    /// about it *now*: the digests come from the project page this resolve
+    /// just read, so a file republished with different content is not
+    /// answered from what was cached under the old one.
+    fn cached_metadata(
+        document: &str,
+        name: &pep508_rs::PackageName,
+        version: &pep440_rs::Version,
+        candidate: &Candidate,
+    ) -> Result<WheelMetadata, String> {
+        if let Some(digests) = &candidate.core_metadata {
+            verify_digest(document.as_bytes(), digests, "metadata file", &candidate.wheel.name)?;
+        }
+        parse_metadata(document, name, version, &candidate.wheel.name)
+    }
+
     /// Read a document from the index, against this resolve's budget and
     /// this deployment's route policy. Returns the bytes and the URL they
     /// were read from, which relative links resolve against.
@@ -379,14 +403,25 @@
     /// Where `url`'s document is cached. The route scope keys the
     /// namespace, so a private index cached under one caller's credential
     /// is never read back for a caller who does not reproduce that scope.
-    fn cache_path(&self, auth: &AuthHeaders, url: &url::Url) -> PathBuf {
+    /// Where the document read from `url` is cached. `derived_from` is the
+    /// digest of the artifact a document was extracted from rather than
+    /// read whole, and joins the key so a republished artifact is read
+    /// again rather than answered from what came out of the old one.
+    fn cache_path(
+        &self,
+        auth: &AuthHeaders,
+        url: &url::Url,
+        derived_from: Option<&str>,
+    ) -> PathBuf {
         let scope = match auth.metadata_scope(url.as_str(), None) {
             MetadataCacheScope::Public => "public".to_string(),
             MetadataCacheScope::Private { descriptor_id } => descriptor_id,
         };
-        self.cache_dir
-            .join(scope)
-            .join(format!("{}.json", pnpm_crypto_hash::create_hex_hash(url.as_str())))
+        let key = match derived_from {
+            Some(digest) => format!("{url}#{digest}"),
+            None => url.to_string(),
+        };
+        self.cache_dir.join(scope).join(format!("{}.json", pnpm_crypto_hash::create_hex_hash(&key)))

Incorporate the file's integrity hash into the cache key to prevent using stale
or mismatched cached metadata.

pnpr/crates/pnpr/src/resolver/pypi.rs [281]

-let cache_path = self.cache_path(&auth, &metadata_url(&wheel_url));
+let metadata_location = metadata_url(&wheel_url);
+let integrity = candidate
+    .core_metadata
+    .as_ref()
+    .unwrap_or(&candidate.wheel.hashes);
+let integrity = serde_json::to_string(integrity)
+    .map_err(|err| format!("serialize the integrity of {}: {err}", candidate.wheel.name))?;
+let cache_path = self.cache_path(
+    &auth,
+    &metadata_location,
+    Some(&integrity),
+);
Suggestion importance[1-10]: 7

__

Why: While it correctly identifies a critical flaw where cached metadata circumvents hash verification, the suggested code passes an undefined third argument to cache_path causing a compilation error.

Medium
✅ Suggestions up to commit 4933980
CategorySuggestion                                                                                                                                    Impact
High-level
✅ Caching wheels and serializing bytes as JSON arrays causes severe bloat
Suggestion Impact:The commit replaces cached byte vectors with text strings and refactors fetching so raw wheels are not cached. For wheel fallbacks, it downloads the wheel, extracts and validates METADATA, and caches only that metadata document.

code diff:

     /// One wheel's `METADATA`, from the file the index publishes beside it
     /// when it publishes one, and out of the wheel itself when it does not.
+    ///
+    /// What is cached is the metadata document either way, so a wheel is
+    /// downloaded at most once for a version, and never again.
     async fn metadata(
         &self,
         name: &pep508_rs::PackageName,
+        version: &pep440_rs::Version,
         candidate: &Candidate,
     ) -> Result<WheelMetadata, String> {
         let canonical_name = canonical_project_name(name)?;
         let wheel_url = url::Url::parse(&candidate.wheel.url)
             .map_err(|err| format!("parse the wheel URL for {name}: {err}"))?;
         validate_url(&wheel_url).map_err(|err| super::report_message(&err))?;
-        if let Some(digests) = &candidate.core_metadata {
-            let metadata_url = format!("{}.metadata", candidate.wheel.url);
-            let metadata_url = url::Url::parse(&metadata_url)
-                .map_err(|err| format!("build the metadata URL for {name}: {err}"))?;
+        let auth = self.auth_for(&canonical_name);
+        let cache_path = self.cache_path(&auth, &metadata_url(&wheel_url));
+        if let Some(cached) = self.cached(&cache_path).await {
+            let document = self.hold("metadata", cached.body)?;
+            return parse_metadata(&document, name, version, &candidate.wheel.name);
+        }
+        let _reading = self.locks.lock(&cache_path.to_string_lossy()).await;
+        if let Some(cached) = self.cached(&cache_path).await {
+            let document = self.hold("metadata", cached.body)?;
+            return parse_metadata(&document, name, version, &candidate.wheel.name);
+        }
+        let document = if let Some(digests) = &candidate.core_metadata {
             let (document, _) = self
-                .read(&metadata_url, &canonical_name, "metadata", MAX_METADATA_BYTES, None)
+                .fetch(&auth, &metadata_url(&wheel_url), "metadata", MAX_METADATA_BYTES, None)
                 .await?;
-            verify_digest(document.as_bytes(), digests, "metadata file", &candidate.wheel.name)?;
-            return WheelMetadata::parse(&document).map_err(|err| super::report_message(&err));
-        }
-        let (wheel, _) =
-            self.read_bytes(&wheel_url, &canonical_name, "wheel", MAX_WHEEL_BYTES, None).await?;
-        verify_digest(&wheel, &candidate.wheel.hashes, "wheel", &candidate.wheel.name)?;
-        let document = metadata_from_wheel(&wheel, &candidate.wheel.name)?;
-        WheelMetadata::parse(&document).map_err(|err| super::report_message(&err))
-    }
-
-    /// Read a document, from the cache when it is still fresh and from the
-    /// index otherwise. Returns the document and the URL it was read from,
-    /// which relative links in it resolve against.
-    async fn read(
+            verify_digest(&document, digests, "metadata file", &candidate.wheel.name)?;
+            document
+        } else {
+            let (wheel, _) = self.fetch(&auth, &wheel_url, "wheel", MAX_WHEEL_BYTES, None).await?;
+            verify_digest(&wheel, &candidate.wheel.hashes, "wheel", &candidate.wheel.name)?;
+            metadata_from_wheel(&wheel, &candidate.wheel.name)?
+        };
+        let document = text(document, "metadata", &candidate.wheel.name)?;
+        let metadata = parse_metadata(&document, name, version, &candidate.wheel.name)?;
+        Self::store(cache_path, CachedDocument { url: wheel_url.to_string(), body: document })
+            .await;
+        Ok(metadata)
+    }
+
+    /// Read a document from the index, against this resolve's budget and
+    /// this deployment's route policy. Returns the bytes and the URL they
+    /// were read from, which relative links resolve against.
+    async fn fetch(
         &self,
+        auth: &AuthHeaders,
         url: &url::Url,
-        canonical_name: &str,
-        kind: &str,
-        limit: usize,
-        accept: Option<&str>,
-    ) -> Result<(String, url::Url), String> {
-        let (bytes, source) = self.read_bytes(url, canonical_name, kind, limit, accept).await?;
-        let document =
-            String::from_utf8(bytes).map_err(|err| format!("decode the {kind} at {url}: {err}"))?;
-        Ok((document, source))
-    }
-
-    async fn read_bytes(
-        &self,
-        url: &url::Url,
-        canonical_name: &str,
         kind: &str,
         limit: usize,
         accept: Option<&str>,
     ) -> Result<(Vec<u8>, url::Url), String> {
-        let auth = self.auth_for(canonical_name);
-        let cache_path = self.cache_path(&auth, url);
-        if let Some(cached) = self.cached(&cache_path).await {
-            let source = cached.url(url)?;
-            return Ok((self.hold(kind, cached.body)?, source));
-        }
-        let _reading = self.locks.lock(&cache_path.to_string_lossy()).await;
-        if let Some(cached) = self.cached(&cache_path).await {
-            let source = cached.url(url)?;
-            return Ok((self.hold(kind, cached.body)?, source));
-        }
         if !within_budget(self.bytes_held.load(Ordering::Relaxed)) {
             return Err(budget_exhausted(kind));
         }
+        // The route policy decides what this deployment may reach at all;
+        // an index a caller merely names is refused here rather than
+        // fetched (SSRF boundary).
         if !auth.allows_fetch(url.as_str()) {
             return Err(format!(
                 "{url} is not allowed by this pnpr server; the operator must declare its \
@@ -307,7 +333,7 @@
             .client
             .get_limited_bytes_with_secure_auth_and_retry(
                 url.as_str(),
-                &auth,
+                auth,
                 accept,
                 RetryOpts::default(),
                 limit,
@@ -322,16 +348,14 @@
         }
         let source = url::Url::parse(&response.url)
             .map_err(|err| format!("parse the URL the {kind} was read from: {err}"))?;
-        let body = self.hold(kind, response.body)?;
-        Self::store(cache_path, CachedDocument { url: source.to_string(), body: body.clone() })
-            .await;
-        Ok((body, source))
+        Ok((self.hold(kind, response.body)?, source))
     }
 
     /// Account bytes against this resolve's budget, which bounds what one
     /// request can make the server hold and cache.
-    fn hold(&self, kind: &str, body: Vec<u8>) -> Result<Vec<u8>, String> {
-        let held = self.bytes_held.fetch_add(body.len(), Ordering::Relaxed) + body.len();
+    fn hold<Body: AsRef<[u8]>>(&self, kind: &str, body: Body) -> Result<Body, String> {
+        let held =
+            self.bytes_held.fetch_add(body.as_ref().len(), Ordering::Relaxed) + body.as_ref().len();
         if held > MAX_TOTAL_BYTES {
             return Err(budget_exhausted(kind));
         }
@@ -388,13 +412,77 @@
     }
 }
 
+/// The candidates a project page offers, refusing a page that is not one.
+fn parse_page(
+    page: &str,
+    page_url: &url::Url,
+    name: &pep508_rs::PackageName,
+    target: &Target,
+) -> Result<BTreeMap<pep440_rs::Version, Candidate>, String> {
+    candidates_from_page(page, page_url, name, target).map_err(|err| super::report_message(&err))
+}
+
+/// A document as text, refusing one that is not.
+fn text(bytes: Vec<u8>, kind: &str, of: &str) -> Result<String, String> {
+    String::from_utf8(bytes).map_err(|err| format!("decode the {kind} of {of}: {err}"))
+}
+
+/// The metadata a document describes, refusing one that describes another
+/// distribution: what a wheel requires decides what a client installs, so
+/// metadata for something else must not stand in for it.
+fn parse_metadata(
+    document: &str,
+    name: &pep508_rs::PackageName,
+    version: &pep440_rs::Version,
+    filename: &str,
+) -> Result<WheelMetadata, String> {
+    let metadata = WheelMetadata::parse(document).map_err(|err| super::report_message(&err))?;
+    let named = metadata
+        .name
+        .parse::<pep508_rs::PackageName>()
+        .map_err(|err| format!("read the distribution the metadata of {filename} names: {err}"))?;
+    let versioned = metadata
+        .version
+        .parse::<pep440_rs::Version>()
+        .map_err(|err| format!("read the version the metadata of {filename} names: {err}"))?;
+    if named != *name || versioned != *version {
+        return Err(format!(
+            "the metadata of {filename} describes {named} {versioned}, not {name} {version}",
+        ));
+    }
+    Ok(metadata)
+}
+
+/// The project page of `canonical_name` under an index, keeping whatever
+/// query the index URL carries: an index can put a token there, and a page
+/// addressed without it is a different request.
+fn project_page_url(index: &url::Url, canonical_name: &str) -> Result<url::Url, String> {
+    let mut url = index.clone();
+    url.set_path(&format!("{}{canonical_name}/", index.path()));
+    Ok(url)
+}
+
+/// The metadata file published beside a wheel (PEP 658), which is the
+/// wheel's own address with `.metadata` on the end of its path — the query
+/// stays where it is.
+fn metadata_url(wheel: &url::Url) -> url::Url {
+    let mut url = wheel.clone();
+    url.set_path(&format!("{}.metadata", wheel.path()));
+    url
+}
+
 /// A document as it was read, beside the URL it came from: a redirected
 /// page's links resolve against where it landed, not where it was asked
 /// for.
+///
+/// The body is text, which is what both cached documents are — a Simple
+/// API page and a `METADATA` file — and what keeps the cache entry the
+/// size of the document rather than the decimal array JSON would make of
+/// its bytes.
 #[derive(serde::Serialize, serde::Deserialize)]
 struct CachedDocument {
     url: String,
-    body: Vec<u8>,
+    body: String,
 }

Modify CachedDocument to avoid serializing byte arrays into massive JSON arrays
(e.g., using base64 or serde_bytes). Additionally, avoid caching entire raw
wheels in read_bytes and cache only the extracted METADATA to prevent
significant memory and disk bloat.

Examples:

pnpr/crates/pnpr/src/resolver/pypi.rs [394-398]
pnpr/crates/pnpr/src/resolver/pypi.rs [326-328]

Solution Walkthrough:

Before:

#[derive(serde::Serialize, serde::Deserialize)]
struct CachedDocument {
    url: String,
    body: Vec<u8>, // Serializes to a massive JSON array of integers for wheels
}

async fn read_bytes(...) -> Result<(Vec<u8>, url::Url), String> {
    // ...
    // Caches the entire raw wheel (up to 256MB)
    Self::store(cache_path, CachedDocument { url: source.to_string(), body: body.clone() }).await;
    // ...
}

After:

#[derive(serde::Serialize, serde::Deserialize)]
struct CachedDocument {
    url: String,
    #[serde(with = "base64_serde")] // or use `serde_bytes` to avoid JSON array serialization
    body: Vec<u8>,
}

async fn metadata(...) -> Result<WheelMetadata, String> {
    // ...
    // Bypass caching the full wheel in `read_bytes` (e.g. `fetch_bytes_without_caching`), 
    // and manually cache only the extracted METADATA document instead.
    let wheel = self.fetch_bytes_without_caching(&wheel_url, ...).await?;
    let document = metadata_from_wheel(&wheel, ...)?;
    // Cache the extracted `document` here to avoid holding and re-processing 256MB wheels.
    // ...
}
Suggestion importance[1-10]: 9

__

Why: This suggestion correctly identifies a severe performance and memory issue where caching raw wheels via serde_json creates massive JSON arrays of integers, leading to OOMs and significant disk bloat.

High
Possible issue
✅ Use normalized project name for simple index URL
Suggestion Impact:The raw-name URL construction was replaced by project_page_url(&self.index, &canonical_name), and that helper appends the canonical name to the index path.

code diff:

-        let page_url = self
-            .index
-            .join(&format!("{name}/"))
-            .map_err(|err| format!("build the index URL for {name}: {err}"))?;
         let canonical_name = canonical_project_name(name)?;
-        let (page, page_url) = self
-            .read(
-                &page_url,
-                &canonical_name,
-                "page",
-                MAX_PAGE_BYTES,
-                Some(pnpr_pypi::JSON_CONTENT_TYPE),
-            )
+        let page_url = project_page_url(&self.index, &canonical_name)?;

Update the index URL construction to use the normalized project name
(canonical_name) instead of the raw name.

pnpr/crates/pnpr/src/resolver/pypi.rs [215-219]

+let canonical_name = canonical_project_name(name)?;
 let page_url = self
     .index
-    .join(&format!("{name}/"))
+    .join(&format!("{canonical_name}/"))
     .map_err(|err| format!("build the index URL for {name}: {err}"))?;
-let canonical_name = canonical_project_name(name)?;
Suggestion importance[1-10]: 9

__

Why: Using the unnormalized project name for the index URL violates PEP 503 and can cause HTTP 404 errors for packages with non-standard casing or punctuation.

High
Ignore invalid wheel names instead of failing

Modify wheel_identity to return Ok(None) rather than bailing out when an invalid
wheel filename or version string is encountered. This allows the resolver to
gracefully ignore malformed packages instead of aborting the entire resolution.

pnpm/crates/python-resolver/src/candidates.rs [106-127]

 pub fn wheel_identity(
     filename: &str,
     tags: &[String],
 ) -> Result<Option<(PackageName, Version, usize)>> {
     let Some(stem) = filename.strip_suffix(".whl") else { return Ok(None) };
     let parts = stem.split('-').collect::<Vec<_>>();
     if !(parts.len() == 5 || parts.len() == 6) || filename.contains(['/', '\\']) {
-        bail!("invalid Python wheel filename: {filename}");
+        return Ok(None);
     }
     let wheel_tags = &parts[parts.len() - 3..];
     let rank = tags.iter().position(|tag| {
         let actual = tag.split('-').collect::<Vec<_>>();
         actual.len() == 3
             && wheel_tags.iter().zip(actual).all(|(supported, actual)| {
                 supported.split('.').any(|supported| supported == actual)
             })
     });
-    rank.map(|rank| {
-        Ok((parts[0].parse().into_diagnostic()?, parts[1].parse().into_diagnostic()?, rank))
-    })
-    .transpose()
+    Ok(rank.and_then(|rank| {
+        Some((parts[0].parse().ok()?, parts[1].parse().ok()?, rank))
+    }))
 }
Suggestion importance[1-10]: 8

__

Why: Registries often have malformed wheel names in older versions; failing the entire resolution process over one invalid entry is a significant bug that this suggestion elegantly fixes.

Medium

Comment thread pnpr/crates/pnpr/src/resolver/pypi.rs Resolved
Comment thread pnpr/crates/pnpr/src/resolver/pypi.rs Resolved
Comment thread pnpm/crates/cli/src/python/tests.rs Resolved
@qodo-code-review

Copy link
Copy Markdown

Code review by qodo was updated up to the latest commit e94bc5c

@qodo-code-review

Copy link
Copy Markdown

Code review by qodo was updated up to the latest commit 4b5c674

Comment thread pnpm/crates/cli/src/python.rs Resolved
Resolution lived inside the CLI, where it could only run beside an
interpreter: the pubgrub provider read a `Registry` that downloads wheels
and asks `host.py` what they require. A registry server resolving on a
client's behalf can do neither, so the rules move to
`pnpm-python-resolver` and the fetching stays with whoever can do it.

The crate owns what resolution decides: which wheel of a version a target
installs, how a requirement's markers and extras constrain a solution,
what a wheel's `METADATA` says, and what the resulting `pylock.toml`
records. `step` runs one pubgrub pass and either solves the project or
names the one distribution or wheel it still needs, which is the shape
the CLI's loop already had — the provider raised the same two requests as
errors for the caller to satisfy.

The CLI keeps everything that needs the interpreter: probing it, reading
a downloaded wheel through `host.py`, ingesting wheels into the store,
and building the environment. Its `Registry` now records each wheel twice
over: the interpreter's full report for installing it, and the subset
resolution reads.

Related to #14599.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_0144Yvv9aAbx93cWtenkzVwG
@qodo-code-review

Copy link
Copy Markdown

Code review by qodo was updated up to the latest commit 4833b6d

zkochan and others added 9 commits September 6, 2026 12:34
`POST /-/pnpr/v0/resolve` now reads `"ecosystem": "pypi"` beside npm and
Cargo. The body carries the project's requirements and the interpreter
they are for; the answer is the `pylock.toml` document the client writes.

Python is where a server-side resolve earns the most. Resolving a
requirement reads a distribution's `METADATA`, which lives inside a
wheel, so a client resolving alone downloads whole wheels for versions it
then rejects. pnpr reads the metadata file an index publishes beside each
wheel (PEP 658, either spelling of the field), falls back to the wheel
itself only for an index that publishes none, and keeps what it read for
every client that follows.

No interpreter runs on the server: the marker environment and the wheel
tags travel in the request as the client's own, and wheels are matched
against them by the shared resolver crate.

Reads are bounded and scoped as the Cargo path's are — the index origin
must be on the route allowlist, each read is classified by the project it
is for so an upstream's per-project rules decide the credential and the
cache namespace, a cold read is fetched once across concurrent resolves,
and per-resolve caps bound the distributions, the metadata reads, each
response, and the bytes one request holds.

The route hook that binds a package name into a fetch is shared with the
Cargo path now, and names what it carries: the ecosystem's canonical
spelling of a package's name, never a version of one.

Related to #14599.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_0144Yvv9aAbx93cWtenkzVwG
`pnpm install` sends a Python project's requirements and its interpreter
to the server configured in `pnprServer`, and writes the `pylock.toml`
that comes back. What it saves is the download resolution otherwise
needs: reading what a distribution requires means reading a wheel's
`METADATA`, so a client resolving alone downloads whole wheels for
versions it then rejects.

The answer is checked, not taken. The lockfile has to record the inputs
this install asked about, the wheels it names are downloaded and checked
against the digests the index published, and the project is re-solved
against the metadata of what actually arrived — the path a lockfile
written by an earlier install already takes. A server that answers with
someone else's project, or with a package the requirements do not reach,
fails the install rather than installing anything.

Asking a server which ecosystems it resolves is now one memo for both
Cargo and Python, keyed by server and ecosystem, so a workspace with
roots of both kinds asks once for each rather than once per root.

Related to #14599.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_0144Yvv9aAbx93cWtenkzVwG
Resolution decides which versions a client installs, so a metadata
document that is not the one the index vouched for must not reach the
solver. A metadata file published with digests is checked against them,
and a wheel read for its metadata is checked against the digest the
project page carries.

An index that publishes no SHA-256 for a file leaves nothing to check
here. The client checks every wheel it downloads regardless, so this is
the server declining to resolve against bytes it can already tell are
wrong, not the only thing standing between a project and a bad wheel.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_0144Yvv9aAbx93cWtenkzVwG
The README's accelerator section named npm and Cargo. It now says what
Python resolution saves a client, which is the reason to point a Python
project at a pnpr server at all.

Also settles two style rules on the new tests: a derive list in the
resolver crate's declared order, and the trailing commas the macro rule
asks for.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_0144Yvv9aAbx93cWtenkzVwG
Review fixes for the Python resolve path.

A document was cached as soon as it arrived, so a project page that is
not one, or metadata that describes another distribution, was served to
every resolve that followed for the whole TTL. Both are now parsed and
checked first and cached only if they hold up. What is kept for a wheel
is the metadata document rather than the wheel, so an index that
publishes no metadata file costs one download per version ever, not one
per resolve.

Metadata is checked against the candidate it was read for: a document
naming another distribution or version is refused, as the client's own
read of the downloaded wheel already refuses it.

A wheel's `METADATA` read past the size cap was cut short rather than
refused, and a document cut short still names its distribution — the
requirements after the cut would simply not exist. It is refused now.

An index URL's query survives every read. An index that carries a token
there was losing it when a project page was addressed, and the metadata
file beside a wheel was addressed by appending to the whole URL rather
than to its path.

A request's requirements and wheel tags are capped: every tag is compared
against every wheel filename, so an unbounded list is work a caller hands
the server. The wheel-read cap drops to 64 MiB, well above an ordinary
wheel.

Client-side, a returned lockfile has to agree with the project's own
`requires-python` as well as its inputs, or the next install would
consider what was just written stale.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_0144Yvv9aAbx93cWtenkzVwG
Two assertions in the Python resolver's unit tests wrapped onto several
lines when they were reformatted, which the macro rule wants a trailing
comma for.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_0144Yvv9aAbx93cWtenkzVwG
A cache entry held its document as bytes, which JSON writes as an array
of decimal numbers: several times the document on disk and in memory for
every read. Both cached documents — a Simple API page and a `METADATA`
file — are text, and are stored as text now. A wheel is not cached at
all; what a wheel is read for is the metadata document inside it.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_0144Yvv9aAbx93cWtenkzVwG
A cached metadata document was answered without asking what the index
says about it now. The digests come from the project page a resolve just
read, and a page entry can expire while the metadata entry outlives it —
the metadata is written when some resolve first needs that version, not
when the page was read — so a file republished under the same URL could
be answered from what was cached for the old one. A cache hit is checked
against the digests in hand.

Client-side, the check that a server answered this install's question is
its own function now, with the test to match: the previous one asserted a
property of its fixture rather than the behaviour.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_0144Yvv9aAbx93cWtenkzVwG
The doc enumerated what the check compares, which the function's
parameters already say. What is left is why the check exists: a lockfile
that answers another question would be written, read back as stale by the
next install, and fail a frozen one outright.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_0144Yvv9aAbx93cWtenkzVwG
Comment thread pnpm/crates/cli/src/python/tests.rs Resolved
…in for

`server_lockfile` says what the doc comment above it said, so the comment
goes.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_0144Yvv9aAbx93cWtenkzVwG
@qodo-code-review

Copy link
Copy Markdown

Code review by qodo was updated up to the latest commit 3013392

@qodo-code-review

Copy link
Copy Markdown

Code review by qodo was updated up to the latest commit ee1f583

greptile-apps[bot]
greptile-apps Bot previously approved these changes Sep 6, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants