Skip to content

feat(pnpr): multiple-uplink fallback ordering per package - #12648

Merged
zkochan merged 3 commits into
mainfrom
feat/pnpr-multi-uplink-fallback
Jun 25, 2026
Merged

zkochan merged 3 commits into
mainfrom
feat/pnpr-multi-uplink-fallback

Conversation

@juanpicado

@juanpicado juanpicado commented Jun 25, 2026 •

Copy link
Copy Markdown
Member

Let a proxy: rule name an ordered list of uplinks (proxy: npmjs private, or the YAML sequence form) and walk it as a fallback chain, matching verdaccio's serial first-success semantics: try uplinks in declared order, stop at the first that answers, and fall through to the next on a 404 or an availability failure. A later private uplink can host a package the primary 404s.

  • config: PackageAccess.proxy becomes an ordered AccessSpec list; Config::resolve_uplinks returns the chain (skipping unknown names); resolve_uplink stays as a primary-only convenience.
  • packument: walk the chain, sending each uplink only its own cached validators. The cache holds one shared body, so its validators are scoped to that body's origin uplink (the validator map is replaced, not merged, on every write) — a conditional GET only ever reaches the origin, so a 304 can only confirm the bytes actually on disk and can't revalidate another origin's body. The freshness window (maxage) comes from the primary uplink only.
  • tarball: try each uplink in order; integrity binds the streamed bytes, so the serving uplink decides whether they are mirrored (caches()) while the cache read is gated on whether any uplink caches.
  • fallthrough is restricted to availability failures (RegistryError::allows_uplink_fallthrough): transport errors, an open circuit, and upstream 5xx. Any authoritative 4xx (401/403 auth, 429 throttle, 400/410, …) stops the walk immediately so a later uplink can't mask the primary's rejection of a scoped or rate-limited request.

Out of scope (left to a later change): verdaccio's full cross-uplink metadata merge and per-version origin tracking. pnpr stays first-success fallback with one cache entry per package.

Summary

Implements the Multiple-uplink fallback ordering per package checklist item of the pnpr↔verdaccio backend-parity tracking issue.

Related to pnpm/tasks#19 — this is a tracking issue covering many parity items, so this PR is intentionally linked without a closing keyword and must not auto-close it on merge.

Squash Commit Body

feat(pnpr): multiple-uplink fallback ordering per package

Let a `proxy:` rule name an ordered list of uplinks
(`proxy: npmjs private`, or the YAML sequence form) and walk it as a
fallback chain, matching verdaccio's serial first-success semantics:
try uplinks in declared order, stop at the first that answers, and fall
through to the next on a 404 or an availability failure. A later private
uplink can host a package the primary 404s.

- config: PackageAccess.proxy becomes an ordered AccessSpec list;
  Config::resolve_uplinks returns the chain (skipping unknown names);
  resolve_uplink stays as a primary-only convenience.
- packument: walk the chain, sending each uplink only its own cached
  validators. The cache holds one shared body, so its validators are
  scoped to that body's origin uplink (the validator map is replaced, not
  merged, on every write) — a conditional GET only ever reaches the
  origin, so a 304 can only confirm the bytes actually on disk and can't
  revalidate another origin's body. The freshness window (maxage) comes
  from the primary uplink only.
- tarball: try each uplink in order; integrity binds the streamed bytes,
  so the serving uplink decides whether they are mirrored (caches())
  while the cache read is gated on whether any uplink caches.
- fallthrough is restricted to availability failures
  (RegistryError::allows_uplink_fallthrough): transport errors, an open
  circuit, and upstream 5xx. Any authoritative 4xx (401/403 auth, 429
  throttle, 400/410, ...) stops the walk immediately so a later uplink
  can't mask the primary's rejection of a scoped or rate-limited request.

Out of scope (left to a later change): verdaccio's full cross-uplink
metadata merge and per-version origin tracking. pnpr stays first-success
fallback with one cache entry per package.

Part of pnpm/tasks#19.

Checklist

  • Added or updated tests (config resolve_uplinks parsing/ordering; integration fallback cases: primary 5xx/404 fallback, all-404, hard-4xx no-fallthrough, tarball fallback, stale-cache; error classifier unit test; storage origin-scoped-validators test).
  • Local CI-parity checks pass: cargo fmt --all --check, cargo clippy --locked --workspace --all-targets -D warnings, cargo nextest run -p pnpr, doc build with -D warnings, typos, and cargo dylint.

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

Summary by CodeRabbit

  • New Features
    • Package proxy settings now accept ordered fallback lists (space-separated or YAML sequence) to try multiple upstreams in sequence.
    • Packument and tarball requests now use an ordered upstream fallback chain for improved availability.
  • Bug Fixes
    • Tarball requests immediately return NotFound when no upstreams match; failover no longer triggers for hard upstream rejections.
    • Cache validation and revalidation now track conditional validators per upstream, improving correctness across fallbacks.
  • Documentation
    • Clarified stale cache behavior and the meaning of the stale cache tag in multi-uplink scenarios.

Let a `proxy:` rule name an ordered list of uplinks
(`proxy: npmjs private`, or the YAML sequence form) and walk it as a
fallback chain, matching verdaccio's serial first-success semantics:
try uplinks in declared order, stop at the first that answers, and fall
through to the next on a 404 or transport/circuit failure. A later
private uplink can host a package the primary 404s; a transient error on
one uplink never surfaces as an authoritative 404 the client would cache
as "gone".

- config: `PackageAccess.proxy` becomes an ordered `AccessSpec` list;
  `Config::resolve_uplinks` returns the chain (skipping unknown names);
  `resolve_uplink` stays as a primary-only convenience.
- packument: walk the chain, sending each uplink only its own cached
  validators (an ETag is origin-specific, so replaying one uplink's
  against another could spuriously 304). Validators are now stored in a
  per-uplink map keyed by uplink name; an older single-object sidecar
  degrades to one unconditional refetch.
- tarball: try each uplink in order; integrity binds the streamed bytes,
  so the serving uplink decides whether they are mirrored (`caches()`)
  while the cache read is gated on whether any uplink caches.
- the cache freshness window (`maxage`) comes from the primary uplink.

Out of scope (left to a later change): verdaccio's full cross-uplink
metadata merge and per-version origin tracking. pnpr stays first-success
fallback with one cache entry per package.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@coderabbitai

coderabbitai Bot commented Jun 25, 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: Pro Plus

Run ID: aa282eb0-9884-445c-b1f7-8fce7d0a8ab2

📥 Commits

Reviewing files that changed from the base of the PR and between d20c0e7 and 8c1ffd6.

📒 Files selected for processing (2)
  • pnpr/crates/pnpr/src/server.rs
  • pnpr/crates/pnpr/tests/server.rs
🚧 Files skipped from review as they are similar to previous changes (2)
  • pnpr/crates/pnpr/tests/server.rs
  • pnpr/crates/pnpr/src/server.rs

📝 Walkthrough

Walkthrough

Ordered uplink lists now drive package proxy resolution, cache validators are stored per uplink, and tarball/packument serving falls back across multiple upstreams with per-uplink revalidation. Tests cover config parsing, storage behavior, and two-uplink server flows.

Changes

Multi-uplink proxy and cache fallback

Layer / File(s) Summary
Ordered proxy resolution
pnpr/crates/pnpr/src/config.rs, pnpr/crates/pnpr/src/config/tests.rs, pnpr/crates/pnpr/src/lib.rs
PackageAccess.proxy accepts AccessSpec, resolve_uplinks returns ordered uplink chains from the first matching package rule, and config tests cover string, list, unknown, first-match, and empty-proxy cases.
Fallthrough eligibility
pnpr/crates/pnpr/src/error.rs, pnpr/crates/pnpr/src/error/tests.rs
RegistryError::allows_uplink_fallthrough classifies upstream availability failures for proxy-chain fallback, and its tests cover 5xx, unavailable, 4xx, and non-upstream cases.
Per-uplink validator storage
pnpr/crates/pnpr/src/upstream.rs, pnpr/crates/pnpr/src/storage.rs, pnpr/crates/pnpr/src/storage/tests.rs
ValidatorsByUplink stores cache validators by uplink name, CachedPackument::Stale and Storage::write_cached_packument use it, and storage tests read and write the per-uplink sidecar format.
Multi-upstream request handling
pnpr/crates/pnpr/src/server.rs, pnpr/crates/pnpr/tests/server.rs
serve_tarball and load_packument_bytes walk ordered upstream chains, fetch or revalidate across multiple uplinks, and server tests cover the fallback and stale-cache paths.

Sequence Diagram(s)

sequenceDiagram
  participant Client
  participant server
  participant Storage
  participant Upstream
  Client->>server: request tarball or packument
  server->>Storage: load cache entry / validators
  loop ordered upstreams
    server->>Upstream: fetch or conditional GET
    Upstream-->>server: bytes, 304, 404, or error
  end
  server->>Storage: store refreshed body or per-uplink validators
  server-->>Client: response or stale fallback
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

  • pnpm/pnpm#12195: Modifies PNPR cache storage and server.rs request handling around cached packuments and proxy reads/writes.
  • pnpm/pnpm#12239: Changes packument revalidation and validator persistence in the same server/storage flow.
  • pnpm/pnpm#12570: Also modifies tarball serving and upstream/cache interaction in pnpr/crates/pnpr/src/server.rs.

Suggested labels

product: pnpr

Suggested reviewers

  • zkochan
✨ 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 feat/pnpr-multi-uplink-fallback

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.

@codecov-commenter

codecov-commenter commented Jun 25, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 92.30769% with 12 lines in your changes missing coverage. Please review.
✅ Project coverage is 88.61%. Comparing base (54c5c0e) to head (8c1ffd6).

Files with missing lines Patch % Lines
pnpr/crates/pnpr/src/server.rs 88.23% 12 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main   pnpm/pnpm#12648      +/-   ##
==========================================
+ Coverage   88.58%   88.61%   +0.03%     
==========================================
  Files         339      339              
  Lines       49171    49277     +106     
==========================================
+ Hits        43557    43667     +110     
+ Misses       5614     5610       -4     

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@juanpicado
juanpicado marked this pull request as ready for review June 25, 2026 05:25
@juanpicado
juanpicado requested a review from zkochan as a code owner June 25, 2026 05:25
Copilot AI review requested due to automatic review settings June 25, 2026 05:25
@qodo-free-for-open-source-projects

Copy link
Copy Markdown

PR Summary by Qodo

pnpr: Support ordered multi-uplink fallback per package (Verdaccio-style)
✨ Enhancement 🧪 Tests 🕐 40+ Minutes

Grey Divider

Description

• Allow proxy: rules to declare an ordered uplink fallback chain per package.
• Walk uplinks serially for packuments and tarballs, falling through on 404/errors.
• Store packument validators per uplink to avoid cross-origin ETag/304 confusion.
Diagram

graph TD
  C(["Client"]) --> S["pnpr server"] --> R["Config::resolve_uplinks"] --> U{{"Ordered uplink chain"}} --> X[["HTTP uplinks"]]
  S --> K[("Storage cache")]
  K --> S
  X --> S

  subgraph Legend
    direction LR
    _client(["Client"]) ~~~ _svc["Service"] ~~~ _cfg{{"Decision/chain"}} ~~~ _db[("Cache") ] ~~~ _ext[["External"]]
  end
Loading
High-Level Assessment

The following are alternative approaches to this PR:

1. Separate cache entries per uplink (packument + tarballs)
  • ➕ Avoids any ambiguity about which uplink produced cached metadata/bytes
  • ➕ Eliminates validator-map merge/race concerns
  • ➕ Simplifies future work on per-version origin tracking
  • ➖ More disk usage and more cache misses across uplinks
  • ➖ Bigger behavioral change vs Verdaccio-like 'one cache per package' mirroring
  • ➖ More invasive changes to storage layout and lookup paths
2. Parallel (racing) uplink fetches instead of serial fallback
  • ➕ Lower tail latency when the primary is slow/failing
  • ➕ Can reduce time-to-first-byte for tarballs in degraded scenarios
  • ➖ Does not match Verdaccio's ordered 'first-success' semantics
  • ➖ Increases upstream load and complicates error precedence rules
  • ➖ Harder to reason about caching and logging
3. Verdaccio-style metadata merge across uplinks
  • ➕ Closer parity with Verdaccio in mixed public/private hosting
  • ➕ Could expose versions scattered across uplinks simultaneously
  • ➖ Significantly more complex: merge policy, conflict resolution, and origin tracking
  • ➖ Requires deeper cache model changes (per-version provenance)
  • ➖ Out of scope for a first-success fallback feature

Recommendation: The PR’s approach (serial ordered fallback with per-uplink validators but a single cached packument body) is the best fit for the stated goal: Verdaccio-like first-success behavior without taking on full cross-uplink metadata merging. The per-uplink validator map is the key correctness choice to prevent spurious 304s when failing over between origins.

Files changed (8) +632 / -131

Enhancement (4) +322 / -117
config.rsSupport ordered 'proxy:' uplink lists and expose 'resolve_uplinks' +59/-19

Support ordered 'proxy:' uplink lists and expose 'resolve_uplinks'

• Changes 'PackageAccess.proxy' from a single uplink name to an 'AccessSpec' (string-or-list) to represent an ordered fallback chain. Adds ordered token extraction for 'proxy:' and introduces 'Config::resolve_uplinks' (skipping unknown uplinks), while keeping 'resolve_uplink' as a primary-only convenience.

pnpr/crates/pnpr/src/config.rs

server.rsImplement serial fallback across uplinks for packuments and tarballs +188/-81

Implement serial fallback across uplinks for packuments and tarballs

• Replaces single-upstream resolution with ordered 'resolve_upstreams', then walks the chain for packuments (Modified/NotModified win; 404 falls through; errors are remembered). Introduces per-uplink validator usage, serves stale cached packuments when all uplinks fail, and adds tarball fallback logic that prefers surfacing errors over returning an authoritative 404 when any uplink errored.

pnpr/crates/pnpr/src/server.rs

storage.rsPersist per-uplink packument validators in cache sidecar +29/-17

Persist per-uplink packument validators in cache sidecar

• Changes cached packument stale metadata from a single 'CacheValidators' to 'ValidatorsByUplink' and updates cache write/read paths accordingly. Implements best-effort backward compatibility by treating unreadable/malformed or legacy sidecar shapes as empty, forcing an unconditional refetch on the next refresh.

pnpr/crates/pnpr/src/storage.rs

upstream.rsAdd 'ValidatorsByUplink' and expose 'Upstream::name()' +46/-0

Add 'ValidatorsByUplink' and expose 'Upstream::name()'

• Introduces 'ValidatorsByUplink' as a persisted map from uplink name to 'CacheValidators', with semantics for get/set and clearing empty validators. Adds 'Upstream::name()' to reliably key validator entries by configured uplink name.

pnpr/crates/pnpr/src/upstream.rs

Refactor (1) +4 / -4
lib.rsRe-export 'AccessSpec' for downstream test/config construction +4/-4

Re-export 'AccessSpec' for downstream test/config construction

• Updates public exports to include 'AccessSpec', enabling callers/tests to construct ordered proxy lists programmatically.

pnpr/crates/pnpr/src/lib.rs

Tests (3) +306 / -10
tests.rsAdd unit tests for 'proxy:' ordering, skipping unknown uplinks, and rule matching +100/-0

Add unit tests for 'proxy:' ordering, skipping unknown uplinks, and rule matching

• Adds tests covering both 'proxy: a b' and 'proxy: [a, b]' forms, ordered resolution, and Verdaccio-style first-match-wins behavior. Verifies unknown uplink names are silently ignored and storage-only packages yield an empty uplink chain.

pnpr/crates/pnpr/src/config/tests.rs

tests.rsUpdate cache tests to assert validators keyed by uplink name +28/-9

Update cache tests to assert validators keyed by uplink name

• Adjusts packument cache tests for the new per-uplink validator map, introducing a fixed uplink name used for assertions. Ensures validator sidecar behavior (write, clear-on-empty, malformed degradation) remains correct under the new shape.

pnpr/crates/pnpr/src/storage/tests.rs

server.rsAdd integration tests for multi-uplink fallback and stale-cache behavior +178/-1

Add integration tests for multi-uplink fallback and stale-cache behavior

• Adds helper config that defines a two-uplink chain and new tests covering packument fallback on primary 5xx and 404, all-404 not-found behavior, tarball fallback to secondary, and serving stale cached packuments when all uplinks are unreachable past TTL.

pnpr/crates/pnpr/tests/server.rs

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Adds Verdaccio-like ordered multi-uplink fallback support to pnpr on a per-package basis, allowing proxy: rules to specify an uplink chain and having the server try each uplink in order until one succeeds.

Changes:

  • Extend config parsing so proxy: can be a whitespace-separated string or YAML sequence, producing an ordered uplink chain via Config::resolve_uplinks.
  • Update packument and tarball proxying to walk the uplink chain with first-success semantics, including better handling of 404 vs transport/circuit failures.
  • Store packument conditional-GET validators per uplink (ETag/Last-Modified are origin-specific) and update cache read/write paths + tests accordingly.

Reviewed changes

Copilot reviewed 8 out of 8 changed files in this pull request and generated 1 comment.

Show a summary per file
File Description
pnpr/crates/pnpr/tests/server.rs Adds integration tests for packument/tarball fallback behavior and stale-cache serving when uplinks fail.
pnpr/crates/pnpr/src/upstream.rs Introduces ValidatorsByUplink and exposes Upstream::name() for per-uplink cache keying.
pnpr/crates/pnpr/src/storage/tests.rs Updates cache tests to write/read validators keyed by uplink name.
pnpr/crates/pnpr/src/storage.rs Changes packument cache metadata to store validators per uplink and merges validator maps on write.
pnpr/crates/pnpr/src/server.rs Implements uplink-chain resolution and fallback fetching for packuments and tarballs.
pnpr/crates/pnpr/src/lib.rs Re-exports AccessSpec to support new config surface.
pnpr/crates/pnpr/src/config/tests.rs Adds unit tests for proxy: parsing and resolve_uplinks ordering/unknown-name skipping.
pnpr/crates/pnpr/src/config.rs Changes PackageAccess.proxy to AccessSpec and adds ordered-token extraction + resolve_uplinks.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment on lines +2478 to +2485
// The TTL is a per-package cache property decided before any uplink is
// contacted, so it comes from the primary (first) uplink in the chain
// that sets a `maxage` (verdaccio's knob); otherwise the global
// `packument_ttl` (the `--packument-ttl-secs` flag) applies.
let ttl = upstreams
.iter()
.find_map(|upstream| upstream.maxage())
.unwrap_or(state.inner.config.packument_ttl);

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed — TTL now uses upstreams.first().and_then(maxage) instead of scanning the chain, so only the primary uplink's maxage can set the cache freshness window (else the global packument_ttl). A secondary's maxage no longer affects it.


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

@qodo-free-for-open-source-projects

qodo-free-for-open-source-projects Bot commented Jun 25, 2026 •

Copy link
Copy Markdown

Code Review by Qodo

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

Grey Divider


Action required

1. Tarball cache bypasses hard-4xx 🐞 Bug ⛨ Security
Description
serve_tarball() serves a cached tarball before attempting the uplink fallback chain, so an
authoritative upstream 4xx (401/403/429/etc.) from the primary uplink is never observed on a cache
hit and can be masked. With multi-uplink chains, the new “hard-4xx stops the walk” policy is
therefore unenforced for tarballs whenever the cache contains the bytes.
Code

pnpr/crates/pnpr/src/server.rs[R888-896]

+    let upstreams = resolve_upstreams(state, &name);
+    // Read the cache if any uplink in the chain mirrors tarballs (or there's
+    // no upstream left at all — a leftover mirror). Reading is harmless: the
+    // bytes are verified against the version's `dist.integrity` before being
+    // served, whichever uplink originally wrote them.
+    let should_read_cache = upstreams.is_empty() || upstreams.iter().any(|u| u.caches());
  if should_read_cache {
      match state.inner.storage.open_cached_tarball(&name, &filename).await {
          Ok(Some((file, len))) => {
Evidence
The tarball handler serves the cache and returns before contacting upstreams, so the hard-4xx stop
logic (documented in allows_uplink_fallthrough and enforced only in the upstream-walk) cannot run on
cache hits.

pnpr/crates/pnpr/src/server.rs[888-940]
pnpr/crates/pnpr/src/error.rs[200-220]

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

## Issue description
`serve_tarball()` returns a cached tarball before contacting any upstream when `should_read_cache` is true. This means the new hard-4xx policy (do not mask authoritative upstream 4xx) is bypassed entirely on cache hits, and a previously cached tarball can be served even if the primary uplink would now reject the request.
### Issue Context
The PR introduces `RegistryError::allows_uplink_fallthrough()` specifically to prevent masking authoritative upstream 4xx responses across the `proxy:` chain. That enforcement currently only happens inside the upstream-walk code (`fetch_tarball_with_fallback()`), but the tarball cache fast-path returns before that logic runs.
### Fix Focus Areas
- pnpr/crates/pnpr/src/server.rs[888-940]
- pnpr/crates/pnpr/src/error.rs[200-220]
- pnpr/crates/pnpr/src/upstream.rs[285-374]
### Implementation direction (one acceptable approach)
- Treat the tarball cache as a fallback, not a pre-check, when an upstream chain exists:
- Attempt the uplink chain first.
- If the chain returns `NotFound`, return 404.
- If the chain returns a hard 4xx (i.e., `!allows_uplink_fallthrough()`), surface it immediately.
- Only fall back to the cached tarball when the chain fails with an *availability* error (transport/open circuit/5xx), similar to packument’s stale fallback.
- If you need to preserve the “cache-first” performance for the common case, add origin metadata for cached tarballs (uplink name) and only use cache-first when the cached origin is the primary uplink; otherwise consult the primary uplink first to enforce hard-4xx.
- Add an integration test covering: cached tarball exists, primary uplink returns 403, response must be 502/403-equivalent rather than 200 from cache.

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


2. Hard 4xx serves cached packument ✓ Resolved 📎 Requirement gap ⛨ Security
Description
On a non-fallthrough upstream error (hard 4xx such as 401/403/429), load_packument_bytes() routes
to serve_stale_or_error(...), which can still serve a cached packument body as a successful
response. This masks authoritative upstream auth/throttle rejections and can continue serving
content from cache when the upstream is explicitly denying the request.
Code

pnpr/crates/pnpr/src/server.rs[R2540-2545]

+                tracing::warn!(?err, package = %name.as_str(), uplink = upstream.name(), "upstream packument fetch failed");
+                if !err.allows_uplink_fallthrough() {
+                    // Hard upstream rejection — don't try later uplinks, which
+                    // could answer for a package this one authoritatively
+                    // refused. Fall back to a stale cached body if we have one.
+                    return serve_stale_or_error(state, name, err).await;
Evidence
PR Compliance ID 3 requires correct uplink proxying/caching behavior with safe fallback semantics,
and the code explicitly treats err.allows_uplink_fallthrough() == false (authoritative upstream
4xx) as a signal to stop trying later uplinks, yet it still calls serve_stale_or_error(). Because
serve_stale_or_error() can return PackumentLoad::Ok(bytes) from an existing cache entry, the
hard-4xx rejection does not “surface immediately” as intended and is effectively converted into a
cached success, undermining the contract that upstream 4xx must not be masked (especially for
auth/rate-limit cases).

Uplink proxying and caching provide production parity (headers, conditional GET, fallback, offline)
pnpr/crates/pnpr/src/server.rs[2539-2545]
pnpr/crates/pnpr/src/server.rs[2602-2614]
pnpr/crates/pnpr/src/error.rs[200-220]
pnpr/crates/pnpr/src/server.rs[2514-2546]
pnpr/crates/pnpr/src/server.rs[2598-2614]
pnpr/crates/pnpr/src/upstream.rs[395-412]

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

## Issue description
When an uplink returns an authoritative non-fallthrough error (hard `4xx` like `401`/`403`/`429`), `load_packument_bytes()` currently calls `serve_stale_or_error(...)`, which may return cached packument bytes as success. This masks upstream auth/rate-limit rejections and violates the intended semantics that hard `4xx` must surface immediately and must not be masked by cache or later uplinks.
## Issue Context
- This PR/contract explicitly documents that upstream `4xx` is authoritative (i.e., `RegistryError::allows_uplink_fallthrough()` is false) and should not be masked.
- Despite stopping uplink fallthrough on these errors, the current implementation can still return a cached `PackumentLoad::Ok(bytes)` via `serve_stale_or_error()` whenever a stale cache entry exists, turning an authoritative rejection into a successful cached response.
- Stale-cache fallback should be reserved for availability-style failures (e.g., transport/circuit/5xx) after exhausting the uplink chain (or when `allows_uplink_fallthrough()` is true), not for hard `4xx`.
- Add a unit/integration test that warms the cache, then has the primary uplink return `401`/`403`/`429`, and assert the response remains an error (not cached OK).
## Fix Focus Areas
- pnpr/crates/pnpr/src/server.rs[2514-2546]
- pnpr/crates/pnpr/src/server.rs[2598-2614]

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


3. 4xx falls through uplinks ✓ Resolved 🐞 Bug ⛨ Security
Description
The new fallback loops treat any upstream error as retryable, so an uplink’s authoritative non-404
4xx (e.g. 401/403/429) can be bypassed by successfully fetching from a later uplink. This changes
access/rate-limit semantics and can return data even when the primary uplink explicitly denied or
throttled the request.
Code

pnpr/crates/pnpr/src/server.rs[R2512-2528]

+    for upstream in &upstreams {
+        // Revalidate conditionally when we hold this uplink's validators:
+        // the upstream can answer `304` and save re-downloading an unchanged
+        // packument.
+        let uplink_validators = validators.get(upstream.name());
+        match upstream.fetch_packument(name, &uplink_validators).await {
+            Ok(PackumentFetch::Modified(fetched)) => {
+                return store_fetched_packument(state, name, upstream.name(), fetched).await;
+            }
+            Ok(PackumentFetch::NotModified) => {
+                return serve_revalidated(state, name, upstream, &uplink_validators).await;
+            }
+            Ok(PackumentFetch::NotFound) => continue,
+            Err(err) => {
+                tracing::warn!(?err, package = %name.as_str(), uplink = upstream.name(), "upstream packument fetch failed");
+                last_err = Some(err);
+            }
Evidence
The server’s fallback loops currently continue on any Err, but the upstream layer explicitly
defines non-404 4xx as authoritative client errors (auth/rate-limit) rather than availability
failures; continuing to later uplinks on those errors bypasses that intent.

pnpr/crates/pnpr/src/server.rs[2504-2529]
pnpr/crates/pnpr/src/server.rs[2400-2420]
pnpr/crates/pnpr/src/upstream.rs[386-403]

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

## Issue description
Multi-uplink fallback is intended to fall through on `404` and transport/circuit failures, but the current implementation falls through on **all** `Err` values from an uplink. Because `Upstream::checked()` treats non-404 `4xx` as authoritative client errors (auth/rate-limit/bad request) and surfaces them as `RegistryError::UpstreamStatus`, the server should **not** continue to the next uplink on those statuses.
### Issue Context
- Today, `Err(err)` in the fallback loops includes `RegistryError::UpstreamStatus { status: 401/403/429/... }`.
- Falling through on these statuses can bypass the intended “primary denies / stops” behavior and instead return a successful response from a later uplink.
### Fix Focus Areas
- pnpr/crates/pnpr/src/server.rs[2406-2420]
- pnpr/crates/pnpr/src/server.rs[2512-2529]
### Implementation notes
- In both fallback loops (`fetch_tarball_with_fallback` and the packument uplink loop), pattern-match `RegistryError::UpstreamStatus { status, .. }` and if `400..500` (non-404, which is already handled), **return immediately** with that error instead of continuing.
- Continue falling through only for true availability failures (transport errors, circuit-open, 5xx statuses).

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


View more (1)
4. Cross-uplink 304 mismatch ✓ Resolved 🐞 Bug ⛨ Security
Description
A 304 Not Modified from uplink A can cause pnpr to serve a cached packument body that was last
fetched from uplink B, because the cache stores one shared packument body but keeps validators for
multiple uplinks. This can serve stale/incorrect metadata (and can persist it) even though the
validating uplink never actually validated those bytes.
Code

pnpr/crates/pnpr/src/server.rs[R2516-2523]

+        let uplink_validators = validators.get(upstream.name());
+        match upstream.fetch_packument(name, &uplink_validators).await {
+            Ok(PackumentFetch::Modified(fetched)) => {
+                return store_fetched_packument(state, name, upstream.name(), fetched).await;
+            }
+            Ok(PackumentFetch::NotModified) => {
+                return serve_revalidated(state, name, upstream, &uplink_validators).await;
+            }
Evidence
The server stops on the first uplink that returns NotModified and serves the cached body without
verifying that the cached bytes were fetched from that same uplink, while the storage layer
explicitly merges validators for multiple uplinks into one sidecar even though only one body is
stored. This allows a validator for uplink A to survive after a body is overwritten by uplink B, and
then a later 304 from uplink A will incorrectly “revalidate” uplink B’s bytes.

pnpr/crates/pnpr/src/server.rs[2504-2529]
pnpr/crates/pnpr/src/server.rs[2542-2575]
pnpr/crates/pnpr/src/storage.rs[390-411]
pnpr/crates/pnpr/src/upstream.rs[283-336]

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

## Issue description
`load_packument_bytes()` accepts `PackumentFetch::NotModified` and immediately serves the single cached packument body, but that cached body may have been written by a different uplink than the one that returned 304. This is possible because `Storage::write_cached_packument()` merges validator entries across uplinks while storing only one packument body.
## Issue Context
A `304` only proves that the *origin’s* content hasn’t changed since the validators were issued; it does not validate an arbitrary cached body from another origin. With multi-uplink fallback, the cached body can legitimately change origins over time (e.g. primary errors → secondary serves; later primary returns 304).
## Fix Focus Areas
- pnpr/crates/pnpr/src/server.rs[2478-2575]
- pnpr/crates/pnpr/src/storage.rs[390-411]
### Suggested implementation direction
Pick one of these approaches:
1) **Track origin uplink for the cached body** (e.g. store `origin_uplink` alongside the validators map in the meta sidecar). Only treat a `304` from uplink U as usable when `origin_uplink == U`; otherwise treat it as a miss for that uplink (force an unconditional GET or continue fallback).
2) **If keeping a single shared cached body**, then **do not retain validators for non-origin uplinks**: when writing a new body from uplink U, clear validators for all other uplinks (so you can’t later send a conditional request to an uplink whose bytes are no longer in the cache). This sacrifices some conditional-GET efficiency but preserves correctness.

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



Remediation recommended

5. No negative miss caching 🐞 Bug ➹ Performance
Description
Multi-uplink fallback continues on NotFound across the entire uplink chain for packuments (and
tarballs), but there is no caching of the final “not found anywhere” result, so repeated misses will
re-contact every uplink serially. This can materially increase upstream load and tail latency under
typo/scan traffic or repeated misses.
Code

pnpr/crates/pnpr/src/server.rs[R2514-2539]

+    // Walk the uplink fallback chain in declared order. The first uplink to
+    // return a body (`Modified`) or confirm our cache (`NotModified`) wins;
+    // a `NotFound` falls through to the next (a private uplink later in the
+    // chain may host the package); an *availability* error (transport,
+    // circuit, 5xx) is remembered and the next uplink tried. An authoritative
+    // upstream error (401/403/other hard 4xx) stops the walk immediately —
+    // see [`RegistryError::allows_uplink_fallthrough`] — so a later public
+    // mirror can never mask the primary's rejection of a scoped package. Each
+    // uplink is sent only *its own* cached validators — an `ETag` is
+    // origin-specific, so replaying one uplink's against another could
+    // spuriously `304` and serve stale data.
+    let mut last_err = None;
+    for upstream in &upstreams {
+        // Revalidate conditionally when we hold this uplink's validators:
+        // the upstream can answer `304` and save re-downloading an unchanged
+        // packument.
+        let uplink_validators = validators.get(upstream.name());
+        match upstream.fetch_packument(name, &uplink_validators).await {
+            Ok(PackumentFetch::Modified(fetched)) => {
+                return store_fetched_packument(state, name, upstream.name(), fetched).await;
+            }
+            Ok(PackumentFetch::NotModified) => {
+                return serve_revalidated(state, name, upstream, &uplink_validators).await;
+            }
+            Ok(PackumentFetch::NotFound) => continue,
+            Err(err) => {
Evidence
The packument fallback loop explicitly continues on NotFound for each uplink and only writes cache
entries on Modified/NotModified, meaning an all-404 miss produces no cached state and will
repeat the full walk on every request; the tarball fallback loop has the same NotFound-continues
behavior.

pnpr/crates/pnpr/src/server.rs[2514-2562]
pnpr/crates/pnpr/src/server.rs[2620-2640]
pnpr/crates/pnpr/src/server.rs[2409-2433]

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

## Issue description
With multi-uplink fallback, `NotFound` walks the whole chain; when *every* uplink returns `NotFound`, pnpr currently returns `NotFound` but does not cache that fact. Repeated requests for missing packages/tarballs therefore re-trigger the full uplink walk every time, increasing upstream traffic and tail latency.
### Issue Context
This is new cost introduced by the multi-uplink behavior (serial fallthrough on 404). The goal is to preserve semantics (a later uplink may host a package the primary 404s) while avoiding repeated full-chain misses.
### Fix Focus Areas
- pnpr/crates/pnpr/src/server.rs[2514-2562]
- pnpr/crates/pnpr/src/server.rs[2409-2433]
### Suggested fix
- Introduce a **bounded, TTL-based negative cache** for the “all uplinks returned 404” outcome:
- Key: package name (and optionally endpoint type: packument vs tarball).
- Value: timestamp/expiry.
- TTL should be short (e.g. 10–60s) so newly-published packages appear quickly.
- Bound size (LRU or max entries) to avoid memory growth.
- On an all-404 chain result:
- Insert/update the negative cache entry.
- On request start:
- If negative cache entry is present and unexpired, return `NotFound` immediately without contacting uplinks.
- Clear/ignore the negative cache when any uplink returns a body (`Modified/Ok`) to avoid pinning a package as missing.
(If you prefer persistence, a small on-disk sentinel in the existing cache store with mtime could work too, but in-memory bounded TTL is usually sufficient and lower I/O.)

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


6. Per-request proxy parsing alloc 🐞 Bug ➹ Performance
Description
Config::resolve_uplinks() re-splits proxy: strings and allocates an intermediate token Vec on
every uplink-chain resolution, which happens on hot request paths (packument/tarball). This adds
avoidable CPU/alloc overhead proportional to rule token count and request rate.
Code

pnpr/crates/pnpr/src/config.rs[R1314-1318]

+        proxy
+            .to_ordered_tokens()
+            .into_iter()
+            .filter_map(|name| self.uplinks.get_key_value(name).map(|(k, v)| (k.as_str(), v)))
+            .collect()
Evidence
resolve_uplinks() creates an intermediate token Vec each call, and resolve_upstreams() calls it
on request paths (tarball + packument). This repeated split+alloc is avoidable because proxy rules
are config-static.

pnpr/crates/pnpr/src/config.rs[797-808]
pnpr/crates/pnpr/src/config.rs[1290-1319]
pnpr/crates/pnpr/src/server.rs[2372-2386]
pnpr/crates/pnpr/src/server.rs[2462-2464]
pnpr/crates/pnpr/src/server.rs[888-893]

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

## Issue description
`Config::resolve_uplinks()` calls `AccessSpec::to_ordered_tokens()` which builds a `Vec<&str>` via `split_whitespace().collect()` each time. This repeated parsing and allocation occurs per request in handlers that call `resolve_upstreams()`.
### Issue Context
- Multi-uplink fallback requires ordered uplink lists, but the tokenization work can be moved to config load / normalization.
### Fix Focus Areas
- pnpr/crates/pnpr/src/config.rs[797-808]
- pnpr/crates/pnpr/src/config.rs[1303-1319]
- pnpr/crates/pnpr/src/server.rs[2372-2386]
### Suggested fix
One of:
1) Store `proxy` as an already-tokenized `Vec<String>` (ordered) in `PackageAccess` (or in a compiled config structure) during config parsing, so resolution only does lookups.
2) Avoid the intermediate token Vec by iterating directly:
- For `One`, iterate `spec.split_whitespace()`.
- For `Many`, iterate `items.iter().flat_map(|s| s.split_whitespace())`.
- Then `filter_map` into the result Vec.
This keeps behavior while removing an unnecessary allocation per call.

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


7. resolve_uplink allocates Vec 📎 Requirement gap ➹ Performance
Description
Config::resolve_uplink() now calls resolve_uplinks() and allocates/collects a full Vec just to
return the first element. This adds avoidable allocation and iteration overhead on an API that is
likely to be called on request paths.
Code

pnpr/crates/pnpr/src/config.rs[R1321-1326]

+    /// The primary (first) uplink for `package_name`, or `None` when the
+    /// package is storage-only. A convenience over [`Self::resolve_uplinks`]
+    /// for the single-uplink question.
#[must_use]
pub fn resolve_uplink(&self, package_name: &str) -> Option<(&str, &UplinkConfig)> {
-        let access = self.packages.iter().find_map(|(pattern, access)| {
-            pattern_matches(pattern, package_name).then_some(access)
-        })?;
-        let proxy_name = access.proxy.as_deref()?;
-        self.uplinks.get_key_value(proxy_name).map(|(k, v)| (k.as_str(), v))
+        self.resolve_uplinks(package_name).into_iter().next()
Evidence
PR Compliance ID 3 covers uplink proxying behavior; uplink resolution is part of that hot path. The
new resolve_uplink() implementation always builds a full chain Vec and then discards all but the
first entry.

Uplink proxying and caching provide production parity (headers, conditional GET, fallback, offline)
pnpr/crates/pnpr/src/config.rs[1321-1327]

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

## Issue description
`resolve_uplink()` constructs the entire uplink chain via `resolve_uplinks()` and then takes `.next()`, which unnecessarily allocates a `Vec` and does extra work.
## Issue Context
This is part of uplink resolution, which is on the critical path for proxying/caching behavior.
## Fix Focus Areas
- pnpr/crates/pnpr/src/config.rs[1303-1319]
- pnpr/crates/pnpr/src/config.rs[1321-1327]

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


View more (4)
8. Timeouts multiply across uplinks 🐞 Bug ➹ Performance
Description
Because fallback is implemented as a serial loop, a single request can wait up to the sum of each
uplink attempt’s timeout (30s default per uplink), increasing tail latency and tying up server
capacity when uplinks are slow/unreachable. This amplifies the impact of upstream slowness and makes
request-driven resource exhaustion more feasible as the configured uplink chain grows.
Code

pnpr/crates/pnpr/src/server.rs[R2406-2421]

+async fn fetch_tarball_with_fallback<'a>(
+    upstreams: &[&'a Upstream],
+    name: &PackageName,
+    filename: &str,
+) -> TarballFetch<'a> {
+    let mut last_err = None;
+    for upstream in upstreams {
+        match upstream.fetch_tarball_response(name, filename).await {
+            Ok(FetchOutcome::Ok(response)) => return TarballFetch::Ok(upstream, response),
+            Ok(FetchOutcome::NotFound) => continue,
+            Err(err) => {
+                tracing::warn!(?err, package = %name.as_str(), %filename, uplink = upstream.name(), "upstream tarball fetch failed");
+                last_err = Some(err);
+            }
+        }
+    }
Evidence
The fallback functions iterate uplinks sequentially, and each upstream request applies a per-uplink
reqwest timeout whose default is 30 seconds, so worst-case duration scales with the number of
uplinks tried.

pnpr/crates/pnpr/src/server.rs[2400-2425]
pnpr/crates/pnpr/src/server.rs[2504-2529]
pnpr/crates/pnpr/src/upstream.rs[291-355]
pnpr/crates/pnpr/src/config.rs[438-474]

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

## Issue description
With multi-uplink fallback, packument/tarball requests are attempted sequentially across uplinks. Each attempt applies the uplink-level timeout, so worst-case latency can become ~`N * timeout` (default 30s each), increasing tail latency and server resource usage under upstream slowness.
### Issue Context
The feature intentionally uses serial “first-success” semantics, but it still benefits from a request-scoped deadline/budget so chain length doesn’t linearly multiply worst-case wait time.
### Fix Focus Areas
- pnpr/crates/pnpr/src/server.rs[2406-2425]
- pnpr/crates/pnpr/src/server.rs[2512-2530]
- pnpr/crates/pnpr/src/upstream.rs[291-365]
- pnpr/crates/pnpr/src/config.rs[438-474]
### Implementation notes
- Introduce a request-level time budget for the whole fallback chain (e.g., `tokio::time::timeout(total_budget, ...)` or a `deadline` passed through and enforced per-attempt by setting `timeout = min(uplink.timeout, remaining)`).
- Consider a configurable maximum uplinks tried per request, or document/guard against very long proxy chains.

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


9. Maxage taken from fallback ✓ Resolved 🐞 Bug ➹ Performance
Description
The packument TTL is selected via find_map over the whole uplink chain, so a secondary/fallback
uplink’s maxage can control cache freshness when the primary uplink does not set maxage. This
changes caching semantics and can unexpectedly increase staleness or upstream traffic for
multi-uplink packages.
Code

pnpr/crates/pnpr/src/server.rs[R2482-2485]

+    let ttl = upstreams
+        .iter()
+        .find_map(|upstream| upstream.maxage())
+        .unwrap_or(state.inner.config.packument_ttl);
Evidence
The code derives ttl by iterating over all upstreams and taking the first Some(maxage) found,
rather than only consulting the primary uplink. This is directly visible in
load_packument_bytes().

pnpr/crates/pnpr/src/server.rs[2471-2485]
pnpr/crates/pnpr/src/upstream.rs[270-274]

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

## Issue description
`ttl` is computed by scanning the uplink chain for the first `maxage`, which allows a non-primary uplink to influence the per-package cache freshness window.
## Issue Context
With fallback chains, operators typically expect the *primary* uplink’s cache policy (or the global default) to govern, not an arbitrary later uplink.
## Fix Focus Areas
- pnpr/crates/pnpr/src/server.rs[2471-2485]
### Suggested implementation direction
Change TTL computation to use only the first uplink:
- `let ttl = upstreams.first().and_then(|u| u.maxage()).unwrap_or(state.inner.config.packument_ttl);`
If the intended behavior really is “first uplink in chain that sets maxage,” add an explicit comment in config docs/tests and consider whether this should be configurable, because it is surprising.

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


10. Extra disk read per write ✓ Resolved 🐞 Bug ➹ Performance
Description
Every write_cached_packument() now reads the validator sidecar from disk to merge the per-uplink
map before writing, adding an additional filesystem read on the miss and 304-revalidation paths.
This increases I/O on a hot path (cache refresh) even when the caller already had the validators map
in hand from read_cached_packument_entry().
Code

pnpr/crates/pnpr/src/storage.rs[R408-410]

+        let mut map = self.cached.read_validators(name).await;
+        map.set(uplink, validators.clone());
+        self.cached.write_packument_with_meta(name, bytes, &map).await
Evidence
The new implementation of write_cached_packument() performs a read_validators() call before
writing the packument/meta. The server calls write_cached_packument() on both the miss path and
the 304 revalidation path, so this extra read happens during refreshes (not just rare codepaths).

pnpr/crates/pnpr/src/storage.rs[390-411]
pnpr/crates/pnpr/src/server.rs[2554-2614]

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

## Issue description
`Storage::write_cached_packument()` always performs a sidecar read (`read_validators`) before writing, even on the common refresh paths where the request already read validators earlier.
## Issue Context
This is not a correctness bug, but it adds extra disk I/O on cache refreshes. The impact depends on workload and storage backend, so keep the fix simple and measurable.
## Fix Focus Areas
- pnpr/crates/pnpr/src/storage.rs[390-411]
- pnpr/crates/pnpr/src/server.rs[2491-2614]
### Suggested implementation direction
Consider one of:
- Pass the already-loaded `ValidatorsByUplink` down from `load_packument_bytes()` into `store_fetched_packument()` / `serve_revalidated()` and then into storage so storage can update-and-write without re-reading.
- Add an overload like `write_cached_packument_with_map(name, bytes, map)` for callers that already hold the map.
(Keeping the current best-effort behavior is fine; this is about reducing avoidable I/O.)

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


11. Unredacted error in warn logs 🐞 Bug ⛨ Security
Description
fetch_tarball_with_fallback() logs ?err (Debug) for upstream failures, which includes
RegistryError’s url field and can therefore log full upstream URLs. This bypasses the codebase’s
existing URL-credential redaction used in error_response() via RegistryError::log_message().
Code

pnpr/crates/pnpr/src/server.rs[R2416-2418]

+            Err(err) => {
+                tracing::warn!(?err, package = %name.as_str(), %filename, uplink = upstream.name(), "upstream tarball fetch failed");
+                last_err = Some(err);
Evidence
The warn log in the fallback loop uses Debug (?err). RegistryError’s Upstream variant contains
a raw url: String field, while error_response() deliberately logs a redacted string via
log_message(), which runs redact_url_credentials(). Since uplink URLs are configured as raw
strings, a URL containing credentials would be logged verbatim by the Debug path.

pnpr/crates/pnpr/src/server.rs[2406-2420]
pnpr/crates/pnpr/src/error.rs[6-13]
pnpr/crates/pnpr/src/server.rs[2798-2809]
pnpr/crates/pnpr/src/error.rs[237-239]
pnpr/crates/pnpr/src/error.rs[310-337]
pnpr/crates/pnpr/src/config.rs[415-452]

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

## Issue description
`tracing::warn!(?err, ...)` logs `RegistryError` using Debug formatting, which includes the `url` field. This can leak embedded URL credentials in logs.
## Issue Context
The server already has a redaction mechanism (`RegistryError::log_message()` + `redact_url_credentials`) used by `error_response()`. The fallback-loop warn log should use the same redacted representation.
## Fix Focus Areas
- pnpr/crates/pnpr/src/server.rs[2406-2420]
- pnpr/crates/pnpr/src/error.rs[6-13]
- pnpr/crates/pnpr/src/server.rs[2798-2808]
### Suggested implementation direction
Replace `?err` with a redacted string:
- `let msg = err.log_message(); tracing::warn!(err = %msg, ...);`
(Keep `last_err = Some(err)` afterward; `log_message()` only borrows.)

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



Informational

12. Tarball resolves uplinks twice 🐞 Bug ➹ Performance
Description
serve_tarball() calls load_packument_bytes() (which resolves the uplink chain) and then calls
resolve_upstreams() again, duplicating rule matching and Vec construction per tarball request.
This adds avoidable per-request overhead on a hot endpoint.
Code

pnpr/crates/pnpr/src/server.rs[R888-894]

+    let upstreams = resolve_upstreams(state, &name);
+    // Read the cache if any uplink in the chain mirrors tarballs (or there's
+    // no upstream left at all — a leftover mirror). Reading is harmless: the
+    // bytes are verified against the version's `dist.integrity` before being
+    // served, whichever uplink originally wrote them.
+    let should_read_cache = upstreams.is_empty() || upstreams.iter().any(|u| u.caches());
   if should_read_cache {
Evidence
load_packument_bytes() resolves the uplink chain at the start of packument loading, and
serve_tarball() resolves the chain again after loading the packument, so each tarball request pays
the resolution cost twice.

pnpr/crates/pnpr/src/server.rs[2447-2464]
pnpr/crates/pnpr/src/server.rs[868-894]

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

## Issue description
Tarball requests resolve the uplink fallback chain twice: once inside `load_packument_bytes()` and again in `serve_tarball()` before fetching the tarball. With multi-uplink support, chain resolution is more expensive (pattern scan + tokenization + Vec building), so doing it twice is unnecessary hot-path work.
### Issue Context
`serve_tarball()` needs packument bytes (for version/integrity/OSV) and later needs the uplink chain for the tarball fetch. The chain can be computed once and reused for both.
### Fix Focus Areas
- pnpr/crates/pnpr/src/server.rs[868-940]
- pnpr/crates/pnpr/src/server.rs[2447-2478]
### Suggested fix
- Compute `upstreams = resolve_upstreams(state, &name)` once in `serve_tarball()` (early), and:
- Add a new helper like `load_packument_bytes_with_upstreams(state, name, upstreams: &[&Upstream])` that uses the provided chain for TTL selection and uplink walking (including the empty-chain/orphaned-cache behavior).
- Have `serve_tarball()` call the new helper, then reuse the same `upstreams` for tarball fallback.
This keeps semantics identical but removes duplicated chain resolution + allocation per tarball request.

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


13. Validators cloned per uplink 🐞 Bug ➹ Performance
Description
On stale packument refresh, each uplink attempt calls ValidatorsByUplink::get(), which clones
CacheValidators (including String fields) before passing them into fetch_packument(). This adds
avoidable allocations/copies on a hot request path when the validator entry is non-empty.
Code

pnpr/crates/pnpr/src/server.rs[R2526-2532]

+    for upstream in &upstreams {
+        // Revalidate conditionally when we hold this uplink's validators:
+        // the upstream can answer `304` and save re-downloading an unchanged
+        // packument.
+        let uplink_validators = validators.get(upstream.name());
+        match upstream.fetch_packument(name, &uplink_validators).await {
+            Ok(PackumentFetch::Modified(fetched)) => {
Evidence
The stale-refresh loop calls validators.get(upstream.name()) for each uplink, and get() uses
.cloned() to return an owned CacheValidators, causing string clones when validators are present.

pnpr/crates/pnpr/src/server.rs[2526-2537]
pnpr/crates/pnpr/src/upstream.rs[209-233]

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

## Issue description
`ValidatorsByUplink::get()` returns an owned `CacheValidators` via `.cloned()`, and the packument fallback loop calls it once per uplink attempt. When the cached entry contains an `ETag`/`Last-Modified`, this clones strings unnecessarily.
### Issue Context
This runs on stale-cache refreshes (common for frequently requested packages with a TTL). Network cost dominates, but this is still easy to avoid and keeps the hot path lean.
### Fix Focus Areas
- pnpr/crates/pnpr/src/upstream.rs[209-233]
- pnpr/crates/pnpr/src/server.rs[2526-2537]
### Implementation direction
- Change `ValidatorsByUplink` API to allow borrowing without cloning, e.g.:
- `fn get_ref(&self, uplink: &str) -> Option<&CacheValidators>`
- then in the loop: `let v = validators.get_ref(upstream.name()).unwrap_or(&EMPTY_VALIDATORS);`
- Alternatively, return `Cow<'_, CacheValidators>`.
- Keep the “missing entry => unconditional GET” behavior unchanged.

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


Grey Divider

Qodo Logo

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@pnpr/crates/pnpr/src/server.rs`:
- Around line 2413-2418: In the fallback loops around fetch_tarball_response in
server.rs, stop treating every Err as retryable: only continue to the next
upstream for transport/circuit failures or retryable upstream responses like
5xx, and return immediately for hard upstream status errors such as 401/403.
Update both multi-uplink paths at the locations using match on FetchOutcome and
Err so the first non-retryable upstream failure is surfaced instead of being
masked by a later uplink.
- Around line 2478-2485: The packument TTL selection is currently scanning every
uplink for maxage, but it should only use the primary uplink’s setting and
otherwise fall back to the global packument_ttl. Update the ttl computation in
server::... where upstreams.iter().find_map(...) is used so it checks only the
first uplink in the chain for maxage, preserving the stated primary-only
contract.

In `@pnpr/crates/pnpr/src/storage.rs`:
- Around line 390-410: Reset the validator map when `write_cached_packument`
replaces the cached body: it currently merges other uplinks’ validators via
`read_validators` and `map.set`, which can let a later `304` reuse a validator
for a body fetched from a different origin. Update `write_cached_packument` in
`storage.rs` so the written metadata is scoped to the current `uplink` only, or
introduce origin/body tracking before any merge, and ensure
`write_packument_with_meta` receives validators that cannot be reused across
uplinks.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: a67ee6cf-cbf4-4935-b705-7ddabb4cbb37

📥 Commits

Reviewing files that changed from the base of the PR and between 54c5c0e and f4fab7e.

📒 Files selected for processing (8)
  • pnpr/crates/pnpr/src/config.rs
  • pnpr/crates/pnpr/src/config/tests.rs
  • pnpr/crates/pnpr/src/lib.rs
  • pnpr/crates/pnpr/src/server.rs
  • pnpr/crates/pnpr/src/storage.rs
  • pnpr/crates/pnpr/src/storage/tests.rs
  • pnpr/crates/pnpr/src/upstream.rs
  • pnpr/crates/pnpr/tests/server.rs

Comment thread pnpr/crates/pnpr/src/server.rs Resolved
Comment thread pnpr/crates/pnpr/src/server.rs Resolved
Comment thread pnpr/crates/pnpr/src/storage.rs Resolved
@qodo-free-for-open-source-projects

Copy link
Copy Markdown

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

@github-actions

github-actions Bot commented Jun 25, 2026 •

Copy link
Copy Markdown
Contributor

Integrated-Benchmark Report (Linux)

Commit: 8c1ffd6d11eb

Each scenario reports direct installs and pnpr installs. Bencher consumes pacquet@HEAD and pnpr@HEAD.

Scenario: Isolated linker: fresh restore, cold cache + cold store

Command Mean [s] Min [s] Max [s] Relative
pacquet@HEAD 4.500 ± 0.166 4.334 4.831 1.54 ± 0.08
pacquet@main 4.468 ± 0.140 4.339 4.725 1.53 ± 0.07
pnpr@HEAD 2.929 ± 0.100 2.809 3.107 1.00
pnpr@main 2.987 ± 0.108 2.872 3.158 1.02 ± 0.05
BENCHMARK_REPORT.json
{
  "results": [
    {
      "command": "pacquet@HEAD",
      "mean": 4.499867044759999,
      "stddev": 0.16579779168845812,
      "median": 4.4540078873599995,
      "user": 3.7122152199999996,
      "system": 3.4026363799999992,
      "min": 4.33388329986,
      "max": 4.83060820886,
      "times": [
        4.69378259486,
        4.37925488686,
        4.34960436586,
        4.4672570048599995,
        4.83060820886,
        4.63139788886,
        4.48959037986,
        4.38253304786,
        4.4407587698599995,
        4.33388329986
      ]
    },
    {
      "command": "pacquet@main",
      "mean": 4.46812143286,
      "stddev": 0.1402282235385667,
      "median": 4.43457487036,
      "user": 3.706179519999999,
      "system": 3.41214228,
      "min": 4.33877160086,
      "max": 4.72532723386,
      "times": [
        4.72061209886,
        4.33877160086,
        4.45604579686,
        4.40731702686,
        4.33896465186,
        4.38633865986,
        4.43868751886,
        4.4325923528599995,
        4.43655738786,
        4.72532723386
      ]
    },
    {
      "command": "pnpr@HEAD",
      "mean": 2.92938108336,
      "stddev": 0.10013427116932833,
      "median": 2.88519841736,
      "user": 2.7465938199999993,
      "system": 3.02839188,
      "min": 2.8089532458599997,
      "max": 3.10730344186,
      "times": [
        2.89860557486,
        2.87179125986,
        2.8089532458599997,
        2.87022204886,
        3.0419798768599997,
        2.85890969886,
        2.86313837886,
        3.04879045186,
        2.92411685586,
        3.10730344186
      ]
    },
    {
      "command": "pnpr@main",
      "mean": 2.9867185108600003,
      "stddev": 0.10782771481265706,
      "median": 2.9405766783600003,
      "user": 2.7727089199999995,
      "system": 3.0259817799999995,
      "min": 2.87215083686,
      "max": 3.15813786186,
      "times": [
        2.87215083686,
        3.03850009686,
        2.88497750786,
        2.89203847386,
        3.15813786186,
        3.05803988486,
        2.92975507886,
        3.15243201086,
        2.93411708486,
        2.94703627186
      ]
    }
  ]
}

Scenario: Isolated linker: fresh restore, hot cache + hot store

Command Mean [ms] Min [ms] Max [ms] Relative
pacquet@HEAD 625.8 ± 14.4 608.4 657.4 1.00
pacquet@main 634.4 ± 20.2 616.0 676.5 1.01 ± 0.04
pnpr@HEAD 737.6 ± 141.9 675.0 1139.6 1.18 ± 0.23
pnpr@main 691.5 ± 17.6 664.1 718.6 1.11 ± 0.04
BENCHMARK_REPORT.json
{
  "results": [
    {
      "command": "pacquet@HEAD",
      "mean": 0.62579345892,
      "stddev": 0.014397984375567168,
      "median": 0.6228721923200001,
      "user": 0.3808414399999999,
      "system": 1.3103337400000001,
      "min": 0.6084281448200001,
      "max": 0.6573933738200001,
      "times": [
        0.6264001838200001,
        0.6411583058200001,
        0.6226994698200001,
        0.6230449148200001,
        0.6573933738200001,
        0.6084281448200001,
        0.6128215838200001,
        0.6300614238200001,
        0.6167519208200001,
        0.6191752678200001
      ]
    },
    {
      "command": "pacquet@main",
      "mean": 0.6343883438200001,
      "stddev": 0.02021054127258777,
      "median": 0.6266422548200001,
      "user": 0.3816077399999999,
      "system": 1.3060134399999999,
      "min": 0.6159684898200001,
      "max": 0.67652919982,
      "times": [
        0.6572100368200001,
        0.6306557408200001,
        0.6178068298200001,
        0.6226287688200001,
        0.6369372878200001,
        0.6173666788200001,
        0.67652919982,
        0.6469763188200001,
        0.6218040868200001,
        0.6159684898200001
      ]
    },
    {
      "command": "pnpr@HEAD",
      "mean": 0.7375541911200001,
      "stddev": 0.14190251785144448,
      "median": 0.6939292513200002,
      "user": 0.39731094,
      "system": 1.3634197399999999,
      "min": 0.6749983768200001,
      "max": 1.13955979482,
      "times": [
        0.6819912578200001,
        0.7107769758200001,
        0.6862864798200001,
        0.7101701528200001,
        0.7069601938200001,
        0.6749983768200001,
        0.6775393938200001,
        0.7015720228200001,
        0.6856872628200001,
        1.13955979482
      ]
    },
    {
      "command": "pnpr@main",
      "mean": 0.6915320816200001,
      "stddev": 0.01763119450632881,
      "median": 0.6918548788200001,
      "user": 0.3969512399999999,
      "system": 1.3406992399999997,
      "min": 0.6640705558200001,
      "max": 0.7185837718200001,
      "times": [
        0.7185837718200001,
        0.7038005528200001,
        0.6919334898200001,
        0.66825203182,
        0.6917762678200001,
        0.6818453938200001,
        0.6870309668200001,
        0.6640705558200001,
        0.6941797228200001,
        0.7138480628200001
      ]
    }
  ]
}

Scenario: Isolated linker: fresh install, cold cache + cold store

Command Mean [s] Min [s] Max [s] Relative
pacquet@HEAD 4.812 ± 0.052 4.710 4.896 1.51 ± 0.03
pacquet@main 4.817 ± 0.089 4.708 4.937 1.52 ± 0.04
pnpr@HEAD 3.179 ± 0.063 3.090 3.265 1.00
pnpr@main 3.219 ± 0.110 3.108 3.448 1.01 ± 0.04
BENCHMARK_REPORT.json
{
  "results": [
    {
      "command": "pacquet@HEAD",
      "mean": 4.81209763886,
      "stddev": 0.052314583129154484,
      "median": 4.810997754460001,
      "user": 3.8963776599999997,
      "system": 3.40978946,
      "min": 4.71047667746,
      "max": 4.89602898646,
      "times": [
        4.84547147046,
        4.80558271046,
        4.75219242846,
        4.71047667746,
        4.89602898646,
        4.8537425804600005,
        4.80413777546,
        4.81641279846,
        4.80089023646,
        4.83604072446
      ]
    },
    {
      "command": "pacquet@main",
      "mean": 4.81703761086,
      "stddev": 0.08918653915376426,
      "median": 4.78561472546,
      "user": 3.8883732600000003,
      "system": 3.4088609599999997,
      "min": 4.70842047946,
      "max": 4.93705871946,
      "times": [
        4.90583397246,
        4.88662612546,
        4.92875922446,
        4.93705871946,
        4.71187645046,
        4.77741726246,
        4.77805944546,
        4.70842047946,
        4.74315442346,
        4.79317000546
      ]
    },
    {
      "command": "pnpr@HEAD",
      "mean": 3.1785742174599996,
      "stddev": 0.06325788512519571,
      "median": 3.16737066396,
      "user": 2.8439195600000002,
      "system": 3.1446324599999995,
      "min": 3.09047139646,
      "max": 3.26492230546,
      "times": [
        3.17255908546,
        3.10096863946,
        3.26124465446,
        3.15489145646,
        3.16218224246,
        3.09047139646,
        3.26492230546,
        3.14834072946,
        3.25687576346,
        3.17328590146
      ]
    },
    {
      "command": "pnpr@main",
      "mean": 3.2185505299599995,
      "stddev": 0.10976606617907568,
      "median": 3.18448461996,
      "user": 2.8534494600000007,
      "system": 3.1806130599999998,
      "min": 3.10838916246,
      "max": 3.44788884246,
      "times": [
        3.16718117646,
        3.10838916246,
        3.20178806346,
        3.2576748324600002,
        3.16592293446,
        3.36018608746,
        3.13820804646,
        3.44788884246,
        3.21956042246,
        3.11870573146
      ]
    }
  ]
}

Scenario: Isolated linker: fresh install, hot cache + hot store

Command Mean [s] Min [s] Max [s] Relative
pacquet@HEAD 1.341 ± 0.012 1.322 1.361 1.00
pacquet@main 1.344 ± 0.068 1.308 1.534 1.00 ± 0.05
pnpr@HEAD 1.428 ± 0.070 1.383 1.620 1.06 ± 0.05
pnpr@main 1.420 ± 0.046 1.379 1.541 1.06 ± 0.04
BENCHMARK_REPORT.json
{
  "results": [
    {
      "command": "pacquet@HEAD",
      "mean": 1.34142102082,
      "stddev": 0.012050802146344962,
      "median": 1.33925476992,
      "user": 1.31898496,
      "system": 1.6924059599999999,
      "min": 1.32213567242,
      "max": 1.3606094124199999,
      "times": [
        1.3288413454199999,
        1.32213567242,
        1.33646959642,
        1.3606094124199999,
        1.35211656842,
        1.3384915144199998,
        1.33482408842,
        1.3556493244199999,
        1.34505466042,
        1.34001802542
      ]
    },
    {
      "command": "pacquet@main",
      "mean": 1.34380567942,
      "stddev": 0.0676670553791599,
      "median": 1.32162696842,
      "user": 1.3110213600000002,
      "system": 1.67856466,
      "min": 1.30769111642,
      "max": 1.53368108442,
      "times": [
        1.31959210242,
        1.3210772574199998,
        1.53368108442,
        1.30769111642,
        1.32182157742,
        1.31038505942,
        1.32450169542,
        1.34963337442,
        1.3282411674199999,
        1.32143235942
      ]
    },
    {
      "command": "pnpr@HEAD",
      "mean": 1.42771925972,
      "stddev": 0.06993965329705215,
      "median": 1.4031871654199999,
      "user": 0.5820005599999998,
      "system": 1.5577170599999999,
      "min": 1.38340695542,
      "max": 1.61977062042,
      "times": [
        1.4467512194199998,
        1.38340695542,
        1.4004010814199999,
        1.61977062042,
        1.40124131342,
        1.42674149342,
        1.4083612454199999,
        1.39640639442,
        1.4051330174199999,
        1.3889792564199999
      ]
    },
    {
      "command": "pnpr@main",
      "mean": 1.42034398662,
      "stddev": 0.045758774403746816,
      "median": 1.41122622392,
      "user": 0.5885012599999999,
      "system": 1.5548361599999998,
      "min": 1.37862386842,
      "max": 1.54056246042,
      "times": [
        1.4311660074199999,
        1.54056246042,
        1.42605907742,
        1.3972709054199999,
        1.42502026042,
        1.39501074242,
        1.37862386842,
        1.3872740964199999,
        1.4064268434199998,
        1.41602560442
      ]
    }
  ]
}

Scenario: Isolated linker: fresh install, cold cache + hot store

Command Mean [s] Min [s] Max [s] Relative
pacquet@HEAD 3.046 ± 0.044 2.986 3.123 2.10 ± 0.04
pacquet@main 3.042 ± 0.062 3.001 3.214 2.10 ± 0.05
pnpr@HEAD 1.448 ± 0.015 1.414 1.473 1.00
pnpr@main 1.457 ± 0.018 1.432 1.488 1.01 ± 0.02
BENCHMARK_REPORT.json
{
  "results": [
    {
      "command": "pacquet@HEAD",
      "mean": 3.04633424792,
      "stddev": 0.04383646707561471,
      "median": 3.03980649402,
      "user": 1.7890325,
      "system": 1.9721621599999999,
      "min": 2.98580191352,
      "max": 3.12345519552,
      "times": [
        3.07017922952,
        3.03184764552,
        2.98580191352,
        2.99724506652,
        3.0080837585199998,
        3.03245525052,
        3.12345519552,
        3.04715773752,
        3.08934864152,
        3.07776804052
      ]
    },
    {
      "command": "pacquet@main",
      "mean": 3.04234828682,
      "stddev": 0.06230797419240921,
      "median": 3.0322249990200003,
      "user": 1.80625,
      "system": 1.9612971599999998,
      "min": 3.00142881952,
      "max": 3.21414122252,
      "times": [
        3.00142881952,
        3.03729549652,
        3.00291682552,
        3.02021395552,
        3.0049107515199998,
        3.03409962152,
        3.03390593052,
        3.03054406752,
        3.21414122252,
        3.04402617752
      ]
    },
    {
      "command": "pnpr@HEAD",
      "mean": 1.4475314426199999,
      "stddev": 0.015417562216925442,
      "median": 1.44876908952,
      "user": 0.5882489,
      "system": 1.59948386,
      "min": 1.4142423875199999,
      "max": 1.47344858052,
      "times": [
        1.44772958752,
        1.4590068115200001,
        1.45491679652,
        1.44542682552,
        1.47344858052,
        1.44217720252,
        1.44980859152,
        1.4518201475199999,
        1.43673749552,
        1.4142423875199999
      ]
    },
    {
      "command": "pnpr@main",
      "mean": 1.45727442522,
      "stddev": 0.018100180879253157,
      "median": 1.45568081102,
      "user": 0.6068832,
      "system": 1.5616286599999998,
      "min": 1.43242579252,
      "max": 1.4878511535199999,
      "times": [
        1.47819664252,
        1.47494793652,
        1.4878511535199999,
        1.45650534052,
        1.45893058752,
        1.45485628152,
        1.43931546052,
        1.44658973052,
        1.43242579252,
        1.44312532652
      ]
    }
  ]
}

@github-actions

github-actions Bot commented Jun 25, 2026 •

Copy link
Copy Markdown
Contributor

🐰 Bencher Report

Branchpr/12648
Testbedpacquet
Click to view all benchmark results
BenchmarkLatencyBenchmark Result
milliseconds (ms)
(Result Δ%)
Upper Boundary
milliseconds (ms)
(Limit %)
isolated-linker.fresh-install.cold-cache.cold-store📈 view plot
🚷 view threshold
4,812.10 ms
(+0.94%)Baseline: 4,767.28 ms
5,720.74 ms
(84.12%)
isolated-linker.fresh-install.cold-cache.hot-store📈 view plot
🚷 view threshold
3,046.33 ms
(+0.17%)Baseline: 3,041.08 ms
3,649.30 ms
(83.48%)
isolated-linker.fresh-install.hot-cache.hot-store📈 view plot
🚷 view threshold
1,341.42 ms
(-0.56%)Baseline: 1,348.95 ms
1,618.74 ms
(82.87%)
isolated-linker.fresh-restore.cold-cache.cold-store📈 view plot
🚷 view threshold
4,499.87 ms
(-3.70%)Baseline: 4,672.86 ms
5,607.43 ms
(80.25%)
isolated-linker.fresh-restore.hot-cache.hot-store📈 view plot
🚷 view threshold
625.79 ms
(-0.29%)Baseline: 627.61 ms
753.14 ms
(83.09%)
🐰 View full continuous benchmarking report in Bencher

@github-actions

github-actions Bot commented Jun 25, 2026 •

Copy link
Copy Markdown
Contributor

🐰 Bencher Report

Branchpr/12648
Testbedpnpr

⚠️ WARNING: No Threshold found!

Without a Threshold, no Alerts will ever be generated.

Click here to create a new Threshold
For more information, see the Threshold documentation.
To only post results if a Threshold exists, set the --ci-only-thresholds flag.

Click to view all benchmark results
BenchmarkLatencymilliseconds (ms)
isolated-linker.fresh-install.cold-cache.cold-store📈 view plot
⚠️ NO THRESHOLD
3,178.57 ms
isolated-linker.fresh-install.cold-cache.hot-store📈 view plot
⚠️ NO THRESHOLD
1,447.53 ms
isolated-linker.fresh-install.hot-cache.hot-store📈 view plot
⚠️ NO THRESHOLD
1,427.72 ms
isolated-linker.fresh-restore.cold-cache.cold-store📈 view plot
⚠️ NO THRESHOLD
2,929.38 ms
isolated-linker.fresh-restore.hot-cache.hot-store📈 view plot
⚠️ NO THRESHOLD
737.55 ms
🐰 View full continuous benchmarking report in Bencher

@github-actions github-actions Bot added the reviewed: coderabbit CodeRabbit submitted an approving review label Jun 25, 2026
- Restrict uplink fallthrough to availability failures
  (RegistryError::allows_uplink_fallthrough): transport errors, an open
  circuit, and upstream 5xx. Any authoritative 4xx (401/403 auth, 429
  throttle, 400/410, ...) now stops the walk immediately so a later uplink
  can't mask the primary's rejection of a scoped or rate-limited request.
- Scope cached packument validators to the body's origin uplink: the
  validator map is replaced, not merged, on every write. The cache holds
  one shared body, so a conditional GET only ever reaches that body's
  origin and a 304 can no longer revalidate another origin's bytes.
- Select the packument TTL from the primary uplink's maxage only
  (.first().and_then), not the first uplink in the chain that sets one, so
  a secondary's maxage can't govern the shared cache.

Adds unit coverage for the fallthrough classifier and a storage test for
origin-scoped validators, plus an integration test that a primary 4xx is
not masked by a later uplink.

Part of pnpm/pnpm#11973.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@qodo-free-for-open-source-projects

Copy link
Copy Markdown

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

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (1)
pnpr/crates/pnpr/src/error/tests.rs (1)

157-187: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Cover the transport-error branch too.

allows_uplink_fallthrough() also returns true for RegistryError::Upstream { .. }, but this test only pins the UpstreamStatus(5xx) and UpstreamUnavailable paths. Adding one Upstream case would keep the third allowed branch from regressing silently.

As per path instructions, REVIEW_GUIDE.md says "tests—add regression tests proving failover rules".

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@pnpr/crates/pnpr/src/error/tests.rs` around lines 157 - 187, Add a regression
case in allows_uplink_fallthrough_only_for_availability_failures to cover the
RegistryError::Upstream branch, since the current test only exercises
UpstreamStatus and UpstreamUnavailable. Create an Upstream error instance with
representative url/uplink/body data and assert that allows_uplink_fallthrough()
returns true, keeping the failover rules pinned alongside the existing cases.

Source: Path instructions

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Nitpick comments:
In `@pnpr/crates/pnpr/src/error/tests.rs`:
- Around line 157-187: Add a regression case in
allows_uplink_fallthrough_only_for_availability_failures to cover the
RegistryError::Upstream branch, since the current test only exercises
UpstreamStatus and UpstreamUnavailable. Create an Upstream error instance with
representative url/uplink/body data and assert that allows_uplink_fallthrough()
returns true, keeping the failover rules pinned alongside the existing cases.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: 64aeee4d-5d06-4b17-9148-65ce82adfc5b

📥 Commits

Reviewing files that changed from the base of the PR and between f4fab7e and d20c0e7.

📒 Files selected for processing (7)
  • pnpr/crates/pnpr/src/error.rs
  • pnpr/crates/pnpr/src/error/tests.rs
  • pnpr/crates/pnpr/src/server.rs
  • pnpr/crates/pnpr/src/storage.rs
  • pnpr/crates/pnpr/src/storage/tests.rs
  • pnpr/crates/pnpr/src/upstream.rs
  • pnpr/crates/pnpr/tests/server.rs
🚧 Files skipped from review as they are similar to previous changes (4)
  • pnpr/crates/pnpr/tests/server.rs
  • pnpr/crates/pnpr/src/upstream.rs
  • pnpr/crates/pnpr/src/storage/tests.rs
  • pnpr/crates/pnpr/src/server.rs

@qodo-free-for-open-source-projects

Copy link
Copy Markdown

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

A non-fallthrough upstream error (an authoritative 4xx: 401/403 auth,
429 throttle, 400/410, ...) now returns the error directly rather than
routing through the stale-cache fallback. Serving a cached packument body
on a hard rejection would mask the upstream's denial and keep handing out
content it is now refusing. Stale-cache fallback is retained only for the
case where the whole chain fails with availability errors
(transport/circuit/5xx).

Adds an integration test that a primary 403 surfaces as a gateway error
and does not serve the warmed stale body (and never consults the
secondary); the existing all-uplinks-fail stale test confirms transient
fallback is unchanged.

Part of pnpm/pnpm#11973.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Copilot AI review requested due to automatic review settings June 25, 2026 06:24

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 10 out of 10 changed files in this pull request and generated no new comments.

Comment on lines +888 to 896
let upstreams = resolve_upstreams(state, &name);
// Read the cache if any uplink in the chain mirrors tarballs (or there's
// no upstream left at all — a leftover mirror). Reading is harmless: the
// bytes are verified against the version's `dist.integrity` before being
// served, whichever uplink originally wrote them.
let should_read_cache = upstreams.is_empty() || upstreams.iter().any(|u| u.caches());
if should_read_cache {
match state.inner.storage.open_cached_tarball(&name, &filename).await {
Ok(Some((file, len))) => {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Action required

1. Tarball cache bypasses hard-4xx 🐞 Bug ⛨ Security

serve_tarball() serves a cached tarball before attempting the uplink fallback chain, so an
authoritative upstream 4xx (401/403/429/etc.) from the primary uplink is never observed on a cache
hit and can be masked. With multi-uplink chains, the new “hard-4xx stops the walk” policy is
therefore unenforced for tarballs whenever the cache contains the bytes.
Agent Prompt
### Issue description
`serve_tarball()` returns a cached tarball before contacting any upstream when `should_read_cache` is true. This means the new hard-4xx policy (do not mask authoritative upstream 4xx) is bypassed entirely on cache hits, and a previously cached tarball can be served even if the primary uplink would now reject the request.

### Issue Context
The PR introduces `RegistryError::allows_uplink_fallthrough()` specifically to prevent masking authoritative upstream 4xx responses across the `proxy:` chain. That enforcement currently only happens inside the upstream-walk code (`fetch_tarball_with_fallback()`), but the tarball cache fast-path returns before that logic runs.

### Fix Focus Areas
- pnpr/crates/pnpr/src/server.rs[888-940]
- pnpr/crates/pnpr/src/error.rs[200-220]
- pnpr/crates/pnpr/src/upstream.rs[285-374]

### Implementation direction (one acceptable approach)
- Treat the tarball cache as a fallback, not a pre-check, when an upstream chain exists:
  - Attempt the uplink chain first.
  - If the chain returns `NotFound`, return 404.
  - If the chain returns a hard 4xx (i.e., `!allows_uplink_fallthrough()`), surface it immediately.
  - Only fall back to the cached tarball when the chain fails with an *availability* error (transport/open circuit/5xx), similar to packument’s stale fallback.
- If you need to preserve the “cache-first” performance for the common case, add origin metadata for cached tarballs (uplink name) and only use cache-first when the cached origin is the primary uplink; otherwise consult the primary uplink first to enforce hard-4xx.
- Add an integration test covering: cached tarball exists, primary uplink returns 403, response must be 502/403-equivalent rather than 200 from cache.

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

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is intended behavior, not a bypass — the hard-4xx policy is enforced for tarballs, at the layer that gates them. serve_tarball runs before the cache read: (1) authorize(..., Action::Access) gates the client via pnpr's own access: policy — the upstream's 4xx is about pnpr's service-account credentials, not the client's authorization; (2) load_packument_bytes is called first and applies the full hard-4xx-stops-the-walk / no-stale-on-hard-4xx enforcement and gates which version/integrity are valid (a revoked version 404s once the packument refreshes, bounded by packument_ttl). A cache hit then serves immutable, content-addressed bytes already verified against the packument-declared dist.integrity.

Re-fetching a cached tarball on every request to re-check upstream auth would defeat the mirror and contradict immutable-artifact caching (and matches neither verdaccio nor npm). So no behavior change; I've added a comment at the cache-read site documenting why the policy is enforced upstream of this point so it isn't re-raised.


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

@qodo-free-for-open-source-projects

Copy link
Copy Markdown

Code review by qodo was updated up to the latest commit 8c1ffd6

1 similar comment
@qodo-free-for-open-source-projects

Copy link
Copy Markdown

Code review by qodo was updated up to the latest commit 8c1ffd6

@zkochan
zkochan added this pull request to the merge queue Jun 25, 2026
@github-merge-queue
github-merge-queue Bot removed this pull request from the merge queue due to failed status checks Jun 25, 2026
@zkochan
zkochan merged commit 6aa5b70 into main Jun 25, 2026
34 checks passed
@zkochan
zkochan deleted the feat/pnpr-multi-uplink-fallback branch June 25, 2026 18:53
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

product: pnpr reviewed: coderabbit CodeRabbit submitted an approving review state: automerge

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants